def pie_chart_draw(self, values, llabels): d = Drawing(10, 150) # chart pc = Pie() pc.x = 0 pc.y = 50 # set data pc.data = values # set labels pc.labels = get_percentage(values) # set the link line between slice and it's label pc.sideLabels = 1 # set width and color for slices pc.slices.strokeWidth = 0 pc.slices.strokeColor = None d.add( self.title_draw(250, 180, _('Precipitation probability statistics'))) d.add(pc) d.add( self.legend_draw(llabels, pc, x=300, y=150, boxAnchor='ne', columnMaximum=12, type='pie')) return d
def __init__(self, drawing=None, data=None, x=70, y=25, width=115, height=115): pie = Pie() pie.strokeColor = white pie.slices.strokeColor = white pie.slices.popout = 1 pie.width = width pie.height = height pie.y = y pie.x = x pie.sideLabels = 1 pie.slices.fontName = 'Lato' pie.slices.fontSize = 9 colors = get_n_random_colors(len(data)) for i in range(0, len(data)): pie.slices[i].fillColor = toColor(colors[i]) pie.data = [value for (_, value) in data] pie.labels = [key for (key, _) in data] drawing.add(pie)
def overview_month_spending_breakdown_pie(c, h, w): categories = [ 'Clothing', 'Transport', 'Insurance', 'Food', 'Medical and Dental', 'Housing', 'Utilities', 'Education', 'Gifts', 'Entertainment' ] d = Drawing() pie = Pie() pie.sideLabels = 1 pie._seriesCount = 10 my_data = [] for x in categories: my_data.append(data.category_data(x.lower(), month, 2019)) pie.x = 0 pie.y = 0 pie.width = 100 pie.height = pie.width pie.data = my_data pie.slices.fontName = serif_font pie.slices.fontSize = 11 pie.labels = tuple(categories) pie.slices.strokeWidth = 0.5 #pie.slices[3].popout = 20 d.add(pie) d.drawOn(c, h, w)
def pie_chart_draw(self, values, llabels): d = Drawing(10, 150) # chart pc = Pie() pc.x = 0 pc.y = 50 # set data pc.data = values # set labels percentage = [] for value in values: v = round(value, 2) percentage.append(str(v) + " %") pc.labels = percentage # set the link line between slice and it's label pc.sideLabels = 1 # set width and color for slices pc.slices.strokeWidth = 0 pc.slices.strokeColor = None d.add(self.title_draw(250, 180, 'Student Attendance Percentage')) d.add(pc) d.add( self.legend_draw(llabels, pc, x=300, y=150, boxAnchor='ne', columnMaximum=12, type='pie')) return d
def monthly_spending_breakdown_pie(c, category, h, w, v=False): d = Drawing() pie = Pie() pie.sideLabels = 1 pie._seriesCount = 10 output = [] my_data = [] output = data.cat_ind_data(category, month, year) my_data = output[1] labels = output[0] if sum(my_data) == 0: return pie.x = 0 pie.y = 0 pie.width = 100 pie.height = pie.width pie.data = my_data pie.slices.fontName = serif_font pie.slices.fontSize = 11 pie.labels = labels pie.slices.strokeWidth = 0.5 #pie.slices[3].popout = 20 d.add(pie) d.drawOn(c, h, w)
def overview_budget_spent(c, w, h): my_data = data.monthly_total(year) my_data = my_data[0:month] budget = data.budget() - sum(my_data) my_data.append(budget) my_label = [] label = [ 'January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] for j in range(0, month): my_label.append(label[j]) my_label.append('Budget remaining') d = Drawing() pie = Pie() pie.sideLabels = 1 pie._seriesCount = 10 pie.x = 0 pie.y = 0 pie.width = 100 pie.height = pie.width pie.data = my_data pie.slices.fontName = serif_font pie.slices.fontSize = 11 pie.labels = my_label pie.slices.strokeWidth = 0.5 pie.slices[-1].popout = 20 d.add(pie) d.drawOn(c, w, h)
def monthly_spending_cat_pie(c, category, h, w, v=False): d = Drawing() pie = Pie() pie.sideLabels = 1 pie._seriesCount = 10 spent = 0 my_data = [] for i in range(1, month + 1): spent += int(data.month_code(category, i, year)) print(spent, category) my_data.append(spent) my_data.append(data.code_budget(category) - spent) labels = [f'{category} spending', 'budget left'] if sum(my_data) == 0: return pie.x = 0 pie.y = 0 pie.width = 50 pie.height = pie.width pie.data = my_data pie.slices.fontName = serif_font pie.slices.fontSize = 11 pie.labels = labels pie.slices.strokeWidth = 0.5 #pie.slices[3].popout = 20 d.add(pie) d.drawOn(c, h, w)
def category_budget_left_pie(c, category, h, w): my_data = [] for x in range(1, month + 1): my_data.append(data.category_data(category, x, year)) labels = month_name[1:month + 1] labels.append('Budget') my_data.append(data.category_budget(category) - sum(my_data)) d = Drawing() pie = Pie() pie.sideLabels = 1 pie._seriesCount = 10 #if legend: # add_legend(d, pie, data) pie.x = 0 pie.y = 0 pie.width = 100 pie.height = pie.width pie.data = my_data pie.slices.fontName = serif_font pie.slices.fontSize = 11 pie.labels = labels pie.slices.strokeWidth = 0.5 #pie.slices[3].popout = 20 d.add(pie) d.drawOn(c, h, w)
def getPieChart(): data = [3, 18, 20] chart = Pie() chart.data = data chart.x = 50 chart.y = 5 chart.labels = ['A', 'B', 'C'] title = String(50, 110, 'Pie Chart', fontSize=14) chart.sideLabels = True chart.slices[0].fillColor = colors.red chart.slices[0].popout = 8 legend = Legend() legend.x = 180 legend.y = 80 legend.alignment = 'right' legend.colorNamePairs = Auto(obj=chart) drawing = Drawing(240, 120) drawing.add(title) drawing.add(chart) drawing.add(legend) return drawing
def get_pie_image(width, height, x, y, datas, lables, _colors): """ ��ɱ�״ͼ @param width: ͼƬ��� @param height: ͼƬ�Ŀ�� @param x: ͼƬ��x��� @param y: ͼƬ��y��� @param datas: ���ͼƬ����� @param lables: ��״ͼ��������� """ from reportlab.graphics.charts.piecharts import Pie drawing = Drawing(width, height) pc = Pie() pc.width = 80 pc.height = 80 pc.x = x pc.y = y pc.data = datas pc.labels = lables pc.slices.strokeWidth = 0.5 pc.startAngle = 90 pc.checkLabelOverlap = True pc.sideLabels = True pc.sideLabelsOffset = 0.1 pc.direction = 'clockwise' for i in range(len(lables)): pc.slices[i].fontName = "msyh" pc.slices[i].fontSize = 3 pc.slices[i].labelRadius = 3 pc.slices[i].popout = 5 pc.slices[i].fillColor = _colors[i] drawing.add(pc) return drawing
def create_pie_chart(data, labels, legend=False): from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.shapes import Drawing d = Drawing(250, 275) pie = Pie() # required by Auto pie._seriesCount = len(data) pie.x = 175 pie.y = 100 pie.width = 150 pie.height = 150 pie.data = data pie.labels = labels pie.simpleLabels = 0 pie.sideLabels = True pie.slices.strokeWidth = 0.5 for i in range(0, len(colores)): pie.slices[i].fillColor = colores[i] if legend: add_legend(d, pie, data) d.add(pie) #d.save(formats=['pdf'], outDir='.', fnRoot='test-pie') return d
def on_btnInforme_clicked(self, boton): """ Función que controla el comportamiento del botón "btnInforme". Genera un informe general sobre cuantos clientes hay registrados en cada servicio usando ReportLab. :param boton: :return: """ # añadimos un nuevo dibujo d2 = Drawing(300, 200) tarta = Pie() tarta.x = 65 tarta.y = 15 tarta.height = 170 tarta.width = 170 # tarta.data = [10.456, 20.234, 30.567, 40, 50] tarta.labels = ['Seguro Coche', 'Seguro Moto', 'Sin Seguro'] # porciones # tarta.slices.strokeWidth = 0.5 # tarta.slices[3].popout = 50 # tarta.slices[3].strokeWidth = 5 # tarta.slices[3].strokeDashArray = [5, 2] # pixels de la linea (tamaño) # tarta.slices[3].labelRadius = 1.75 # tarta.slices[3].fontColor = colors.red tarta.sideLabels = 0 cores = [colors.blue, colors.red, colors.green] # coge cada elemento y le asigna un numero for i, color in enumerate(cores): tarta.slices[i].fillColor = color d2.add(tarta) lenda = Legend() lenda.x = 270 lenda.y = 0 lenda.dx = 8 lenda.dy = 8 # espacio entre lineas (?) lenda.fontName = "Helvetica" lenda.fontSize = 8 lenda.boxAnchor = 'n' lenda.columnMaximum = 3 lenda.strokeColor = colors.black lenda.deltax = 75 lenda.deltay = 10 lenda.autoXPadding = 5 lenda.yGap = 0 lenda.dxTextSpace = 5 lenda.alignment = 'right' lenda.dividerLines = 1 | 2 | 4 # lenda.dividerOffsY = 4.5 lenda.subCols.rpad = 30 d2.add(lenda) doc = SimpleDocTemplate("informeGrafica.pdf", pagesize=A4) doc.build([d2])
def readings_and_mix_table(reading_data, mix_data, breakdown, state_emission, location, Elements): ''' Creates 2 tables that are then embedded as the columns of 1 bigger table ''' no_rows = 1 # not used no_cols = 1 col_size = 4.5 readings_table = Table(reading_data, no_cols*[col_size/2*inch], 5*[0.25*inch] + [0.3*inch], hAlign="LEFT") readings_table.setStyle(TableStyle([('FONT', (0,0), (-1,-1), "Times-Roman"), ('FONT', (0,0), (-1,0), "Times-Bold"), ('FONTSIZE', (0,0), (-1,-1), 12), ('FONTSIZE', (0,0), (-1,0), 13), ('ALIGN', (0,0), (0,-1), "RIGHT"), ('VALIGN', (-1,-1), (-1,-1), "TOP")])) d = Drawing(100, 100) pc = Pie() data = [] if state_emission: data = ["Coal", "Oil", "Natural Gas", "Low Carbon"] else: data = ["Coal", "Petroleum", "Natural Gas", "Low Carbon"] for i in range(4): data[i] += ": " + str(round(breakdown[i], 1)) + "%" pc.x = 45 pc.y = 0 pc.width = 55 pc.height = 55 pc.data = breakdown[:4] pc.slices[0].fillColor = colors.Color(202.0/255, 0.0/255, 32.0/255) pc.slices[1].fillColor = colors.Color(244.0/255, 165.0/255, 130.0/255) pc.slices[2].fillColor = colors.Color(5.0/255, 113.0/255, 176.0/255) pc.slices[3].fillColor = colors.Color(146.0/255, 197.0/255, 222.0/255) pc.labels = data pc.slices.strokeWidth=0.5 pc.sideLabels = True d.add(pc) mix_data = [['Energy Mix Data'], [d], ['Location: ' + location]] mix_table = Table(mix_data, no_cols*[col_size/2*inch], [.25*inch, 1*inch, .3*inch], hAlign="RIGHT") mix_table.setStyle(TableStyle([('FONT', (0,0), (-1,-1), "Times-Roman"), ('FONT', (0,0), (0,0), "Times-Bold"), ('FONTSIZE', (0,0), (0,0), 13), ('FONTSIZE', (-1,-1), (-1,-1), 12), ('ALIGN', (0,0), (0,0), "LEFT")])) table_data = [(readings_table, mix_table)] t = Table(table_data, [4.25*inch, 3*inch], hAlign='CENTER') t.setStyle(TableStyle([('VALIGN', (-1,-1), (-1,-1), "TOP")])) Elements.append(t)
def pie_chart(data_for_pie): d = Drawing(400, 400) pc = Pie() pc.x = 100 pc.y = 210 pc.width = 170 pc.height = 170 pc.sideLabels = True pc.sideLabelsOffset = 0.05 car_name_lst = [] car_sales_lst = [] car_price_lst = [] data_for_pie = data_for_pie[1:] data_for_pie = sorted(data_for_pie, key=itemgetter(3), reverse=True) # so i can show 10 most popular cars for i in data_for_pie: car_name = i[1] car_name_lst.append(car_name) car_sales = i[3] car_sales_lst.append(car_sales) car_price = float(i[2].strip( "$")) #by default all the prices are in '', for example '18731.76' car_price_lst.append(car_price) pc.data = car_sales_lst[:10] pc.labels = list(set( car_name_lst[:10])) # by using set i wont have similar items in list d.add(pc, '') """have to done this because in task i have to calculate revenue on Xaxis and car name on Yaxis""" revenue_calculation_1 = car_sales_lst[:10] revenue_calculation_2 = car_price_lst[:10] car_revenue_list = [] for i in range(len(car_price_lst[:10])): reven = revenue_calculation_1[i] * revenue_calculation_2[i] car_revenue_list.append( int(reven)) #using int because its many digits after "," """bar chart """ data = [tuple(car_revenue_list) ] #for some reason bar chart accepts only [[]] or [()] bc = VerticalBarChart() bc.x = 50 bc.y = 0 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 7000000 bc.valueAxis.valueMax = 23000000 bc.valueAxis.valueStep = 1000000 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = list(set(car_name_lst[:10])) d.add(bc) return d
def get2PieChart(): legend = Legend() a = df2.iloc[i, 13] b = df2.iloc[i, 14] c = df2.iloc[i, 15] d = df2.iloc[i, 16] e = df2.iloc[i, 17] da = [a, b, c, d, e] x = 0 y = 0 for i5 in da: if i5 == "Attempted": x = x + 1 else: y = y + 1 data = [x, y] u = round(x * 100 / 5) v = round(y * 100 / 5) h = [u, v] d = [] l = ["%.2f" % i5 for i5 in h] for i5 in l: k = i5.split(".") d.append(k[0]) e = [] j = 0 for i5 in d: #w=i5+"%" j = j + 1 w = i5 + "%" if j == 1: w = w + " (Attempted)" if j == 2: w = w + " (Unattempted)" e.append(w) drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'Attempts', fontSize=14) pie = Pie() pie.sideLabels = True pie.slices.popout = 3 pie.x = 140 pie.y = 60 pie.data = data pie.labels = [letter for letter in e] pie.slices.strokeWidth = 0.5 drawing.add(my_title) n = len(pie.data) setItems(n, pie.slices, 'fillColor', pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i5].fillColor, (pie.labels[i5][0:20], '%0.2f' % pie.data[i5])) for i5 in range(n)] drawing.add(pie) add_legend(drawing, pie, data) return drawing
def draw_Pie(story, ProjectID): d = Drawing(140, 180) pie = Pie() pie.sideLabels = 1 pie.labels = get_story_name_list(ProjectID) pie.data = get_story_count_list(ProjectID) pie.width = 140 pie.height = 140 pie.y = 0 pie.x = 150 d.add(pie) story.append(d)
def draw_Pie(story, ProjectID): d = Drawing(140, 180) pie = Pie() pie.sideLabels = 1 pie.labels= get_story_name_list(ProjectID) pie.data = get_story_count_list(ProjectID) pie.width = 140 pie.height = 140 pie.y = 0 pie.x = 150 d.add(pie) story.append(d)
def __drawPage2LeftPie(self, c): totalHigh = len(self.scanParams['results']['HIGH']) totalMed = len(self.scanParams['results']['MED']) totalLow = len(self.scanParams['results']['LOW']) total = totalHigh + totalMed + totalLow # 第二页,左侧饼图,所有内容书写范围为Pleft:10mm Pright:100mm Pheader:247mm Pfooter:80mm Pleft = START_X + 10 * mm Pright = START_X + 100 * mm Pheader = START_Y + 247 * mm Pfooter = START_Y + 80 * mm #矩形框 c.rect(Pleft, Pheader - 80 * mm, 80 * mm, 80 * mm, fill=0) c.setFont("song", 15) c.drawString(Pleft + 2 * mm, Pheader - 10 * mm, "漏洞等级分布") #饼图 d = Drawing(400, 200) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 70 pc.height = 70 pc.data = [totalHigh, totalMed, totalLow] pc.labels = ['高危', '中危', '低危'] pc.sideLabels = 1 pc.slices.strokeWidth = 0.5 for i in range(3): pc.slices[i].fontName = 'song' #pc.slices[1].fontColor = colors.red pc.slices[1].fillColor = colors.red d.add(pc) #添加饼图到画布 renderPDF.draw(d, c, Pleft + 6 * mm, Pheader - 55 * mm) #底部标注 c.rect(Pleft + 5 * mm, Pheader - 75 * mm, 70 * mm, 8 * mm, fill=0) c.setFont("song", 7) c.circle(Pleft + 8 * mm, Pheader - 71 * mm, 2 * mm, fill=1) c.drawString( Pleft + 11 * mm, Pheader - 72 * mm, "高危(" + str(round((totalHigh / float(total)) * 100, 1)) + "%)") c.circle(Pleft + 28 * mm, Pheader - 71 * mm, 2 * mm, fill=1) c.drawString( Pleft + 31 * mm, Pheader - 72 * mm, "中危(" + str(round((totalMed / float(total)) * 100, 1)) + "%)") c.circle(Pleft + 48 * mm, Pheader - 71 * mm, 2 * mm, fill=1) c.drawString( Pleft + 51 * mm, Pheader - 72 * mm, "低危(" + str(round((totalLow / float(total)) * 100, 1)) + "%)")
def create_pie_chart(self, data_list, label_list, user_color=None): # print data_list # print label_list label_list = map(lambda item: item.upper(), label_list) data = [(item / (sum(data_list) * 1.0)) * 100 for item in data_list] if user_color != None: usage_color = user_color else: random_range = [randint(0, 100) for i in range(len(data_list))] usage_color = map( lambda item: PCMYKColor(randint(0, item), randint(0, item), randint(0, item), randint(0, item)), random_range) print user_color # u_color = [colors.lawngreen, colors.red, colors.gray] # color = [colors.lawngreen, colors.red, colors.gray] # u_master = [randint(0, 100) for i in range(4)] # u_color = [PCMYKColor(randint(0, u_master[0]), randint(0, u_master[1]), randint(0, u_master[2]), randint(0, u_master[3])) for i in range(3)] # print u_color # color = u_color d = Drawing() pie = Pie() pie.x = 200 pie.y = 85 pie.data = data pie.labels = label_list for i, color in enumerate(usage_color): pie.slices[i].fillColor = color pie.slices.strokeWidth = 0.5 pie.slices.popout = 1.5 pie._seriesCount = 3 pie.sideLabels = 1 legend = Legend() legend.alignment = 'right' legend.x = 0 legend.y = 75 legend.colorNamePairs = [ (z, (x, ' {val:.2f}%'.format(val=y))) for x, y, z in zip(pie.labels, data, usage_color) ] d.add(legend) d.add(pie) self.flowables.append(d)
def pie_chart_with_legend(data, answerKey): drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'Pie', fontSize=12) pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in answerKey] pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) add_legend(drawing, pie, data) return drawing
def pie_chart_with_legend(): data = list(range(15, 105, 15)) drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'My Pie Chart', fontSize=14) pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcdefg'] pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) add_legend(drawing, pie, data) return drawing
def graphout(prod_catnames, data): drawing = Drawing(500, 200) pie = Pie() pie.sideLabels = 1 pie.labels = prod_catnames pie.data = data[0] pie.width = 140 pie.height = 140 pie.y = 35 pie.x = 125 pie.slices.popout = 5 drawing.add(pie) return drawing
def simple_pie_chart_side_labels(): data = list(range(15, 105, 15)) drawing = Drawing() pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcdefg'] pie.slices.strokeWidth = 0.5 drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart_side_labels')
def generate(filename, title, additional_info, table_data): styles = getSampleStyleSheet() report = SimpleDocTemplate(filename) report_title = Paragraph(title, styles["h1"]) report_info = Paragraph(additional_info, styles["BodyText"]) table_style = [('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, -1), 'CENTER')] report_table = Table(data=table_data, style=table_style, hAlign="LEFT") empty_line = Spacer(1, 20) sale_per_model = {} #print(table_data) for data in table_data[1:]: #print(data) if data[1].split()[0] not in sale_per_model: sale_per_model[data[1].split()[0]] = data[3] else: sale_per_model[data[1].split()[0]] += int(data[3]) #print(sale_per_model) sorted_sales = sorted(sale_per_model.items(), key=lambda kv: (kv[1], kv[0])) report_pie = Pie() report_pie.sideLabels = 1 report_pie.checkLabelOverlap = 0 report_pie.width = 300 report_pie.height = 200 report_pie.x = 120 report_pie.y = 100 report_pie.data = [] report_pie.labels = [] #print('sorted_sale '*20) #print(sorted_sales) for item in sorted_sales: report_pie.data.append(item[1]) report_pie.labels.append(item[0]) print(len(set(report_pie.labels))) report_chart = Drawing(500, 500) report_chart.add(report_pie) report.build([ report_title, empty_line, report_info, empty_line, report_table, report_chart ])
def add_pie_chart(self, width, height, labels, data, side_labels=False): pad = 15 pc = Pie() pc.x = pad * mm pc.y = pad * mm pc.width = (width - 2 * pad) * mm pc.height = (height - 2 * pad) * mm pc.labels = labels pc.data = data pc.sideLabels = side_labels drawing = Drawing(width * mm, height * mm) drawing.hAlign = "CENTER" drawing.add(pc) self.story.append(drawing)
def pie_chart_with_legend(): data = list(range(15, 105, 15)) drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'My Pie Chart', fontSize=14) pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = None pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) add_legend(drawing, pie, data) drawing.save(formats=['pdf'], outDir='.', fnRoot='pie_chart_with_legend')
def simple_pie_chart_with_title(): data = list(range(15, 105, 15)) drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'My Pie Chart', fontSize=14) pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcdefg'] pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart_with_title')
def pie_chart_with_legend(doc, FI, Equity): data = ['Bond (' + str(FI[-1]) + '%)', 'Equity (' + str(Equity[-1]) + '%)'] drawing = Drawing(width=doc.width / 2, height=250) my_title = String(140, -70, 'Asset-wise Allocation', fontSize=14) pie = Pie() pie.sideLabels = False pie.slices.label_visible = False pie.x = 100 pie.y = -40 pie.width = 200 pie.height = 200 pie.data = [FI[-1], Equity[-1]] pie.labels = data pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) add_legend(drawing, pie, data, doc) return drawing
def draw_pass_fail_piechart(passed_data: List[int]) -> Drawing: passed_data_labels = ['Passed', 'Failed', 'Not run'] d = Drawing(width=200, height=200) pc = Pie() pc.x = 50 pc.y = 50 pc.width = 80 pc.height = 80 pc.slices[0].fillColor = COLOR_GREEN pc.slices[1].fillColor = COLOR_RED pc.slices[2].fillColor = COLOR_GRAY pc.direction = 'anticlockwise' pc.data = passed_data pc.labels = passed_data_labels pc.sideLabels = True pc.slices.fontName = MAIN_FONT_NAME pc.slices.fontSize = AXIS_FONT_SIZE d.add(pc) return d
def _add_pie_chart( self, expense_stats: Dict[str, Tuple], size: int, padding: int, ): if expense_stats: figure = Drawing(self.width, min(size + 2 * padding, self.height)) pie_chart = Pie() pie_chart.x = (self.width - size) / 2 pie_chart.y = padding pie_chart.width = size pie_chart.height = size pie_chart.data = [i[0] for i in expense_stats.values()] pie_chart.labels = list(expense_stats.keys()) pie_chart.slices.strokeWidth = 0.5 pie_chart.sideLabels = True figure.add(pie_chart) self.report_elements.append(figure)
def pie_chart_draw(self, values, llabels): d = Drawing(10, 150) # chart pc = Pie() pc.x = 50 pc.y = 30 # set data pc.data = values # set labels pc.labels = get_percentage(values) # set the link line between slice and it's label pc.sideLabels = 1 # set width and color for slices pc.slices.strokeWidth = 1 pc.slices.strokeColor = None d.add(self.title_draw(180, 140, 'Asistencia')) d.add(pc) d.add(self.legend_draw(llabels, pc, x=290, y=100, boxAnchor='ne', columnMaximum=12, type='pie')) return d
def pdf_drawPie(self, pie_data, pie_lable=[], colors=[], x=805, y=1650, width=900, height=900, innerRadiusFraction=0.5): ''' @example: chart_data = [1212,66,585,225,36] lable = ['dfd','sdd','trtr','rrrr','ytytyt'] self.pdf_drawPie(chart_data,lable) ''' if len(pie_data) == 0 or sum(pie_data) == 0: return d = Drawing(200, 100) pc = Pie() pc.x = 65 pc.y = 65 pc.width = width pc.height = height pc.data = pie_data pc.labels = pie_lable pc.startAngle = 0 pc.sideLabels = 1 pc.simpleLabels = 0 if len(colors) != len(pie_data): colors = [] for i in range(len(pie_data)): colors.append(HexColor(self.randomcolor())) for i in range(0, len(pie_data)): pc.slices[i].fontSize = 40 pc.slices[i].fontName = FONT pc.slices[i].fillColor = colors[i] pc.slices[i].strokeColor = colors[i] pc.innerRadiusFraction = innerRadiusFraction d.add(pc) d.drawOn(self.pdf_page_object, x, y)
def pie_chart_draw(self, values, llabels): d = Drawing(10, 150) # chart pc = Pie() pc.x = 0 pc.y = 50 # set data pc.data = values # set labels pc.labels = get_percentage(values) # set the link line between slice and it's label pc.sideLabels = 1 # set width and color for slices pc.slices.strokeWidth = 0 pc.slices.strokeColor = None d.add(self.title_draw(250, 180, _('Precipitation probability statistics'))) d.add(pc) d.add(self.legend_draw(llabels, pc, x=300, y=150, boxAnchor='ne', columnMaximum=12, type='pie')) return d
def generate_pie_charts(self): self.elements.append( Paragraph( "<u><font color=green>CHARTS</font></u><br/><br/>", ReportPDF.styleH) ) # pie chart for categories pc_cat = Pie() pc_cat.x = 0 pc_cat.width = ReportPDF.pie_charts_w pc_cat.height = ReportPDF.pie_charts_h pc_cat.data = [] pc_cat.labels = [] pc_cat.sideLabels = 1 # pie chart for subcategories pc_subcat = Pie() pc_subcat.x = 250 pc_subcat.width = ReportPDF.pie_charts_w pc_subcat.height = ReportPDF.pie_charts_h pc_subcat.data = [] pc_subcat.labels = [] pc_subcat.sideLabels = 1 # get data for charts for stat, value in self.payments_stat_data.items(): stat_vars = stat.split('_') if stat_vars[1] == 'category': pc_cat.data.append(float(value)) pc_cat.labels.append( get_object_or_404(Category, id=stat_vars[2]) ) elif stat_vars[1] == 'subcategory': pc_subcat.data.append(float(value)) pc_subcat.labels.append( get_object_or_404(Subcategory, id=stat_vars[2]) ) elif stat_vars[1] == 'time': self.lc_data.append(float(value)) self.cat_names.append(stat_vars[2]) # PIE CHARTS IN DRAWING if len(pc_cat.labels) > 1: self.elements.append( Paragraph( "<u><b><font color=green>" "Pie charts for categories and subcategories." "</font></b></u>", ReportPDF.styleN) ) d_pie = Drawing(350, 240) d_pie.add(pc_cat) d_pie.add(pc_subcat) # add charts to PDF self.elements.append(d_pie) float_left = True counter = 0 for category in pc_cat.labels: counter += 1 pc_category = Pie() if float_left: pc_category.x = 0 float_left = False else: pc_category.x = 250 float_left = True pc_category.width = ReportPDF.pie_charts_w pc_category.height = ReportPDF.pie_charts_h pc_category.data = [] pc_category.labels = [] pc_category.sideLabels = 1 subcategories = Subcategory.objects.filter(category=category) for sc_id in list(map(lambda sc: sc.id, subcategories)): # stats for subcategories subcategory_key = 'all_subcategory_{}'.format(sc_id) if self.payments_stat_data.get(subcategory_key, 0): # self.payments_stat_data[subcategory_key] += p_value pc_category.data.append(float(value)) pc_category.labels.append( get_object_or_404(Subcategory, id=sc_id) ) if counter % 2 == 0: d_pie_categories.add(pc_category) if len(pc_cat.labels) % 2 == 0: self.elements.append( Paragraph( "<br/><br/><br/><u><b><font color=green>" "Pie chart for {} and {}." "</font></b></u>".format( last_category, category ), ReportPDF.styleN) ) self.elements.append(d_pie_categories) else: last_category = category d_pie_categories = Drawing(350, 240) d_pie_categories.add(pc_category) if len(pc_cat.labels) % 2 != 0: self.elements.append( Paragraph( "<br/><br/><br/><u><b><font color=green>" "Pie chart for {}." "</font></b></u>".format(category), ReportPDF.styleN) ) self.elements.append(d_pie_categories)
def generar_pdf_busquedas_view(request): print "Genero el PDF" fecha_m = "" resultados=[] fecha_a = "" b=[] t=[] fecha_inicio = x fecha_final = y c=0 r=[] #story =[] response = HttpResponse(content_type='application/pdf') pdf_name = "reporte_busqueda.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) reportes = [] styles = getSampleStyleSheet() fichero_imagen="biblioteca/media/images/Reports-banner.jpg" imagen_logo=Image(os.path.realpath(fichero_imagen),width=400,height=100) reportes.append(imagen_logo) header = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1']) header2 = Paragraph("Reporte de las busquedas realizadas entre la fecha "+str(fecha_inicio)+" hasta la fecha "+str(fecha_final) + "\n", styles['Normal']) salto_linea = Paragraph("\n\n", styles["Normal"]) reportes.append(header) reportes.append(header2) reportes.append(Spacer(1, 12)) headings = ('Busqueda', 'Resultado',)# 'Cantidad_Veces_Buscadas') lista=[] t = Busqueda.objects.all() b = Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct() listar=[] for r in b: print "llllllllllllllllll",r,"\n" if r['resultados'] == False: r['resultados']="No se encontró" listar.append(r) else: r['resultados']="Se encontró" listar.append(r) print "lisygyujgyjgjhbjh", listar #GRAFICAS BARRA total_busquedas=Busqueda.objects.all().count() #TOTAL BUSQUEDAS si=Busqueda.objects.filter(resultados=True).count() #BUSUEDAS ENCONTRADAS (SI) no=total_busquedas-si #BUSQUEDAS NO ENCONTRADAS (NO) #GRAFICAS PASTEL for i in b: print "________________",i.get("busqueda") for j in t: print "===============",j.busqueda if j.busqueda == i.get("busqueda") and j.fecha >= fecha_inicio and j.fecha <= fecha_final: c = c + 1 print c lista.append(c) c=0 print lista , len(lista) li = zip(b,lista) ''' for i in b: print "________________",i.get("busqueda") for j in t: print "===============",j.busqueda if j.busqueda == i.get("busqueda"): c = c + 1 print c lista.append(c) c=0 li = zip(b,lista) ''' #allreportes = [ (i.busqueda, i.resultados) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()] # allreportes = [ i.values() for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()] b=listar allreportes = [ i.values() for i in b] print allreportes t = Table([headings] + allreportes) t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) #GRAFICA DE BARRAS titulo = Paragraph("Busquedas encontradas y no encontradas en el sistema", estilo['title']) drawing = Drawing(400, 200) data = [(si, no)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.bars[0].fillColor = colors.blue bc.bars[1].fillColor = colors.black bc.strokeColor = colors.black bc.fillColor = colors.silver bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = total_busquedas+30 try: r = total_busquedas/2 if type(r) == 'float': bc.valueAxis.valueStep = total_busquedas+0.5 if type(r) == 'int': bc.valueAxis.valueStep = r except: "Nos se puede" bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = ['Encontradas', 'No Encontradas'] drawing.add(bc) bc.barLabels.nudge = 20 bc.barLabelFormat = '%0.0f' bc.barLabels.dx = 0 bc.barLabels.dy = 0 bc.barLabels.boxAnchor = 'n' # irrelevant (becomes 'c') bc.barLabels.fontName = 'Helvetica' bc.barLabels.fontSize = 14 #GRAFICAS DE PASTEL titulo2 = Paragraph("Busquedas y número de veces realizadas", estilo['title']) d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = lista print lista #pc.data = [7, 1, 1, 1, 1, 2] #pc.labels = [ str(i.values()) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda').distinct()] lista_labels = [ str(i.values()) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda').distinct()] #pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6'] pc.sideLabels = 1 pc.width = 150 pc.height = 150 pc.slices.strokeWidth=1#0.5 pc.slices[0].fillColor = colors.yellow pc.slices[1].fillColor = colors.thistle pc.slices[2].fillColor = colors.cornflower pc.slices[3].fillColor = colors.lightsteelblue pc.slices[4].fillColor = colors.aquamarine pc.slices[5].fillColor = colors.cadetblue d.add(pc) legend = Legend() legend.x = 370 legend.y = 0 legend.dx = 10 legend.dy = 10 legend.fontName = 'Helvetica' legend.fontSize = 10 legend.boxAnchor = 'n' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = colors.black legend.deltax = 75 legend.deltay = 10 legend.autoXPadding = 5 legend.yGap = 0 legend.dxTextSpace = 5 legend.alignment = 'right' legend.dividerLines = 1|2|4 legend.dividerOffsY = 4.5 legend.subCols.rpad = 30 #Insertemos nuestros propios colores colores = [colors.blue, colors.red, colors.green, colors.yellow, colors.black, colors.white, colors.silver, colors.pink, colors.brown, colors.orange, colors.purple] for i, color in enumerate(colores): pc.slices[i].fillColor = color legend.colorNamePairs = [( pc.slices[i].fillColor, (lista_labels[i][0:200], '%0.0f' % pc.data[i]) ) for i in xrange(len(pc.data))] d.add(pc) reportes.append(t) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(titulo) reportes.append(drawing) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(titulo2) d.add(legend) reportes.append(d) doc.build(reportes) response.write(buff.getvalue()) buff.close() return response
def ListadoUsos(request): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=num_aprobados_reprobados.pdf; pagesize=A4;' #Esta lista contendra todos los elementos que se dibujaran en el pdf elementos = [] doc = SimpleDocTemplate(response) styleSheet = getSampleStyleSheet() #---> Estilo Titulo el_titulo = styleSheet['Heading1'] el_titulo.alignment = TA_CENTER el_titulo.spaceBefore = 15 el_titulo.fontSize = 12 el_titulo.fontName = 'Helvetica' txtInfo = u'<br />A.C.C.E.M.A:' # Estilo txtInfo info = styleSheet['Normal'] info.fontSize = 12 info.alignment = TA_LEFT info.fontName = 'Helvetica' infoV = Paragraph(txtInfo, info) #-->Estilo tabla x = [ ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('TOPPADDING', (0,0), (-1,-1), 1), ('BOTTOMPADDING', (0,0), (-1,-1), 2), ('GRID', (0,0), (-1,-1), 0.80, colors.black), ('FONT', (0,0), (-1,-1), "Helvetica", 10), ('FONT', (0,0), (1,0), "Helvetica-Bold", 12), ] tabla = [] #--> Titulo de la constancia elementos.append(Spacer(1,5)) Titulo = Paragraph('<b>Estadisticas de usos</b>', el_titulo) elementos.append(Titulo) elementos.append(Spacer(1,5)) #--> Añadiendo la Informción antes del cuadro elementos.append(infoV) elementos.append(Spacer(1,10)) usuarios = User.objects.all() usos = UsosDisp.objects.all() tabla.append([' CANTIDAD DE USUARIOS', u'NÚMERO DE USOS']) tabla.append(['%s'%(usuarios.__len__()), u'%s'%(usos.__len__())]) t1 = Table(tabla, colWidths=('', '')) t1.setStyle(TableStyle(x)) elementos.append(t1) #--> Calculando los porcentajes total = usos.__len__() #--> Frame del gráfico frame = Drawing(350,200) torta = Pie() torta.x = 125 torta.y = 35 torta.width = 120 torta.height = 120 torta.labels = [] contador = 0 for i in usuarios: #import ipdb;ipdb.set_trace() uso_actual = usos.filter(Usuario=i).count() porcen_usuario = (float(uso_actual) * 100) / total torta.labels.append('%3.2f%% %s'%(porcen_usuario, i.username)) torta.data.append(porcen_usuario) #--> Estilos del gráfico torta.slices.labelRadius = 1 torta.sideLabels = 1 torta.slices.fontSize = 8 torta.slices.fontName = 'Helvetica-Bold' torta.slices.strokeWidth = 2 torta.slices.popout = 10 frame.add(torta) elementos.append(frame) doc.build(elementos, canvasmaker=NumeroDePagina ) return response