def sample4pie(): width = 300 height = 150 d = Drawing(width, height) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50] pc.labels = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i"] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 20 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) legend = Legend() legend.x = width - 5 legend.y = height - 5 legend.dx = 20 legend.dy = 5 legend.deltax = 0 legend.boxAnchor = "nw" legend.colorNamePairs = Auto(chart=pc) d.add(legend) return d
def __add_graph(self): drawing = Drawing(200, 100) data = list() labels = list() self.c.drawString(370, 730, 'Distribucion en pesos'.encode('utf-8')) for acc in self.accounts: balance = acc.balance if acc.currency == 'USD': balance = balance * self.dolar data.append(balance) labels.append(acc.name) pie = Pie() pie.x = 280 pie.y = 630 pie.height = 100 pie.width = 100 pie.data = data pie.labels = labels pie.simpleLabels = 1 pie.slices.strokeWidth = 1 pie.slices.strokeColor = black pie.slices.label_visible = 0 legend = Legend() legend.x = 400 legend.y = 680 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'w' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = 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 n = len(pie.data) self.__setItems(n,pie.slices, 'fillColor',self.pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)] drawing.add(pie) drawing.add(legend) x, y = 0, 0 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
def test_24_PieCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.piecharts import Pie pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [13,5,20,22,37,45] pc = Pie() pc.x = 65 pc.y = 15 pc.width = 150 pc.height = 150 pc.data = data pc.labels = ['a','b','c','d','e','f'] d.add(pc) elements.append(d) doc.build(elements)
def test0(self, isFast=0): """Hello World, on a rectangular background. The rectangle's fillColor is yellow. The string's fillColor is red. """ reportlab.rl_config.shapeChecking = not isFast pdfPath = outputfile('test_graphics_speed_fast.pdf') c = Canvas(pdfPath) t0 = time.time() d = Drawing(400, 200) num = 100 for i in range(num): pc = Pie() pc.x = 150 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.labels = ['a','b','c','d','e','f'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 20 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) d.drawOn(c, 80, 500) t1 = time.time() result = 'drew %d pie charts in %0.4f' % (num, t1 - t0) open(outputfile('test_graphics_speed_test%s.log' % (isFast+1)), 'w').write(result)
def sample4pie(): width = 300 height = 150 d = Drawing(width, height) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50] pc.labels = ['0','a','b','c','d','e','f','g','h','i'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 20 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) legend = Legend() legend.x = width-5 legend.y = height-5 legend.dx = 20 legend.dy = 5 legend.deltax = 0 legend.boxAnchor = 'nw' legend.colorNamePairs=Auto(chart=pc) d.add(legend) return d
def __init__(self, width, height, labels, data): IRender.__init__(self, width, height, labels, data) #self.w = self.width #self.h = self.height #data = {} #for value in self.data: # data[value[0]] = int(value[1]) #plot = cairoplot.PiePlot('/tmp/tmp.png', data, self.w*2, self.h*2, gradient=True) ##plot.font_size *= 2 #plot.render() #plot.commit() #with open('/tmp/tmp.png') as f: # self.image = Image(StringIO(f.read()), self.w, self.h) pc = Pie() pc.width = min(self.height,self.width - 150) pc.height = min(self.height - 50,self.width) pc.width = pc.height = min(pc.height, pc.width) pc.x = self.width / 2 - pc.width / 2 pc.y = self.height / 2 - pc.height / 2 pc.data = [int(line[1]) for line in self.data] pc.labels = [line[0] for line in self.data] for i in xrange(len(self.data)): pc.slices[i].fillColor = COLORS[i % len(COLORS)] pc.slices[i].strokeColor = COLORS[i % len(COLORS)] self.drawing = Drawing(self.width, self.height) self.drawing.add(pc)
def draw_time_repartition(mandate): drawing = Drawing(width=180*mm, height=120*mm) pdf_chart_colors = [HexColor("#fa9d00"), HexColor("#006884"), HexColor("#00909e"), HexColor("#ffd08d"), ] pie = Pie() pie.x = 60*mm pie.y = 35*mm pie.width = 60*mm pie.height = 60*mm pie.slices.strokeWidth = 0.5 pie.slices.fontName = 'Helvetica' pie.slices.fontSize = 8 pie.data = [] pie.labels = [] titles = [] add_data_and_titles_to_pie(pie, titles, mandate.research_percent, 'research_percent') add_data_and_titles_to_pie(pie, titles, mandate.tutoring_percent, 'tutoring_percent') add_data_and_titles_to_pie(pie, titles, mandate.service_activities_percent, 'service_activities_percent') add_data_and_titles_to_pie(pie, titles, mandate.formation_activities_percent, 'formation_activities_percent') if len(pie.data) > 0: drawing.add(pie) add_legend_to_pie(drawing) n = len(pie.data) set_items(n, pie.slices, 'fillColor', pdf_chart_colors) drawing.legend.colorNamePairs = \ [(pie.slices[i].fillColor, (titles[i], '%0.f' % pie.data[i] + '%')) for i in range(n)] return drawing
def make_chart(stats): drawing = Drawing() pc = Pie() pc.x = 150 pc.y = 50 pc.data = stats pc.labels = ['Heavily Damaged: %s' % stats[0],'Serverly Damaged: %s' % stats[1]] drawing.add(pc, '') return drawing
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 __init__(self, drawing=None, data=None): #Drawing.__init__(self, width=100, height=175) pie = Pie() pie.strokeColor = white pie.slices.strokeColor = white pie.slices.popout = 1 pie.width = 100 pie.height = 100 pie.y = 50 pie.x = 80 legend = Legend() legend.columnMaximum = 99 legend.alignment = 'right' legend.boxAnchor = 'c' legend.dx = 6 legend.dy = 6 legend.dxTextSpace = 5 legend.deltay = 10 legend.strokeWidth = 0 legend.strokeColor = white legend.subCols[0].minWidth = 75 legend.subCols[0].align = 'left' legend.subCols[1].minWidth = 25 legend.subCols[1].align = 'right' legend.y = 20 legend.x = 128 legend.fontName = 'Lato' legend.fontSize = 9 pie.data = data pie.slices[0].fillColor = lightgrey pie.slices[1].fillColor = limegreen pie.slices[1].popout = 6 pie.slices[2].fillColor = red #pie.slices[2].popout = 1 neutral_pct = positive_pct = negative_pct = 0 total = sum(data) if total > 0: neutral_pct = (data[0] / total) * 100.0 positive_pct = (data[1] / total) * 100.0 negative_pct = (data[2] / total) * 100.0 legend.colorNamePairs = [ (limegreen, ('Positive', '%.1f%%' % positive_pct)), (lightgrey, ('Neutral', '%.1f%%' % neutral_pct)), (red, ('Negative', '%.1f%%' % negative_pct)) ] drawing.add(pie) drawing.add(legend)
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 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 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 diagrammKostenartVonBis(self, aPfad, aDateiname, aData, aLabels): d = Drawing(800, 800) pie = Pie() pie.x = 360 pie.y = 360 pie.xradius = 300 pie.yradius = 300 pie.data = aData pie.labels = aLabels pie.slices.strokeWidth = 0.5 # pie.slices[3].popout = 20 d.add(pie) d.save(formats=['png'], outDir=aPfad, fnRoot=aDateiname)
def getPieChart(c, x, y, data, data_suff, labels, colors, fsize=8.5, radius=0.60, legdx=180, legdy=100): """ Function to draw a Pie Chart """ d = Drawing(200, 200) legend = Legend() legend.columnMaximum = 99 legend.alignment = 'right' legend.dx = 7 legend.dy = 7 legend.dxTextSpace = 5 legend.deltay = 10 legend.strokeWidth = 0 legend.strokeColor = HexColor("0xffffff") legend.subCols[0].minWidth = 75 legend.subCols[0].align = 'left' legend.boxAnchor = 'c' legend.y = legdy legend.x = legdx legend.fontName = "MavenPro" legend.fontSize = 8.5 legendList = [] for k, i in enumerate(colors): legendList.append((HexColor(i), labels[k])) legend.colorNamePairs = legendList pc3 = Pie() pc3.x = 10 pc3.y = 10 pc3.data = data pc3.labels = [str(r) + data_suff if r >= 15 else "" for r in data] pc3.slices.strokeColor = HexColor("0xffffff") pc3.slices.labelRadius = radius pc3.slices.fontName = "MavenPro" pc3.slices.fontSize = fsize pc3.slices.fontColor = HexColor("0xffffff") for k, i in enumerate(colors): pc3.slices[k].fillColor = HexColor(i) d.add(pc3, 'pie3') d.add(legend, 'legend') d.drawOn(c, x, y)
def gopie(): doc = SimpleDocTemplate("products.pdf") Catalog = [] style = styles["Normal"] p = Paragraph("Cranberry Sauce Sales", styles["Heading1"]) Catalog.append(p) d = Drawing(100, 125) cht = Pie() cht.data = sales[0] cht.labels = months cht.slices[0].popout = 10 d.add(cht) Catalog.append(d) doc.build(Catalog)
def simple_pie_chart(): data = [10, 20, 30, 40] drawing = Drawing() pie = Pie() pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcd'] pie.slices.strokeWidth = 0.5 pie.slices[3].popout = 20 pie.slices[3].strokeDashArray = [1, 1] drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart')
def makePie(pdf, SeBAz_contents, total): pdf.saveState() d = Drawing(A4[0] * 6 / 12, A4[1] * 5 / 17) pc = Pie() pc.x = A4[0] * 4 / 12 pc.y = A4[1] * 5 / 17 pc.width = A4[0] * 4 / 12 pc.height = A4[0] * 4 / 12 passd = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'PASS']) faild = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'FAIL']) check = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'CHEK']) excluded = total - (passd + faild + check) pc.data = [passd, faild, excluded, check] pc.simpleLabels = 0 pc.slices.strokeWidth = 0.5 pc.slices.fontName = 'SF-Pro-Rounded-Heavy' pc.slices.fontSize = 8 pc.slices.labelRadius = 1.1 pc.slices[0].popout = 10 pc.slices[0].fillColor = Color(colorPass[0] / 256, colorPass[1] / 256, colorPass[2] / 256, 1) pc.slices[0].fontColor = Color(colorPass[0] / 256, colorPass[1] / 256, colorPass[2] / 256, 1) pc.slices[ 0].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) Passed,'.format( (passd / total) * 100, passd, (passd + faild + check), (passd / (passd + faild + check)) * 100) pc.slices[1].fillColor = Color(colorFail[0] / 256, colorFail[1] / 256, colorFail[2] / 256, 1) pc.slices[1].fontColor = Color(colorFail[0] / 256, colorFail[1] / 256, colorFail[2] / 256, 1) pc.slices[ 1].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) Failed,'.format( (faild / total) * 100, faild, (passd + faild + check), (faild / (passd + faild + check)) * 100) pc.slices[2].fillColor = darkgray pc.slices[2].fontColor = darkgray pc.slices[2].label_text = '{} of {} tests ({:.0f}%) Excluded'.format( excluded, total, (excluded / total) * 100) pc.slices[3].fillColor = Color(colorWarn[0] / 256, colorWarn[1] / 256, colorWarn[2] / 256, 1) pc.slices[3].fontColor = Color(colorWarn[0] / 256, colorWarn[1] / 256, colorWarn[2] / 256, 1) pc.slices[ 3].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) are to be Checked,'.format( (check / total) * 100, check, (passd + faild + check), (check / (passd + faild + check)) * 100) d.add(pc) renderPDF.draw(d, pdf, -A4[0] / 52, -A4[1] / 6) pdf.restoreState()
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 sample4pie(): d = Drawing(400, 200) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50] pc.labels = ['0','a','b','c','d','e','f','g','h','i'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 20 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) return d
def pie_chart(car_data): report_pie = Pie() report_pie.width = 380 report_pie.height = 380 report_pie.x = 42 report_pie.y = -230 report_pie.data = [] report_pie.labels = [] car_make = {} for item in car_data: car_info = format_car(item["car"]) report_pie.data.append(item["total_sales"]) report_pie.labels.append(car_info) report_chart = Drawing() report_chart.add(report_pie) return (report_chart)
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 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 __init__(self, data, labels): super(PieChart, self).__init__(400, 200) colors = [ HexColor("#0000e5"), HexColor("#ff0011"), HexColor("#800000"), HexColor("#e05897"), HexColor("#a08ff7"), HexColor("#8f8ff5"), HexColor("#c7c7fa"), HexColor("#800000"), HexColor("#eb8585"), HexColor("#d60a0a"), HexColor("#ffff00"), HexColor("#1f1feb"), ] # Create pie chart pieChart = Pie() pieChart.x = 40 pieChart.y = 30 pieChart.width = 120 pieChart.height = 120 pieChart.slices.strokeWidth = 0.5 data = json.loads(data) pieChart.data = data pieChart.labels = [] labels = json.loads(labels.replace("'", '"')) for d in data: pieChart.labels.append(str(d)) # Create legend legend = Legend() legend.x = 380 legend.y = 60 legend.boxAnchor = 'se' legend.subCols[1].align = 'right' legend.colorNamePairs = [] len_data = len(data) for i in range(0, len_data): pieChart.slices[i].fillColor = colors[i] legend.colorNamePairs.append((colors[i], labels[i])) self.add(pieChart, "pie chart") self.add(legend, "legend")
def __init__(self, data, labels): super(PieChart, self).__init__(400,200) colors = [ HexColor("#0000e5"), HexColor("#ff0011"), HexColor("#800000"), HexColor("#e05897"), HexColor("#a08ff7"), HexColor("#8f8ff5"), HexColor("#c7c7fa"), HexColor("#800000"), HexColor("#eb8585"), HexColor("#d60a0a"), HexColor("#ffff00"), HexColor("#1f1feb"), ] # Create pie chart pieChart = Pie() pieChart.x = 40 pieChart.y = 30 pieChart.width = 120 pieChart.height = 120 pieChart.slices.strokeWidth=0.5 data = json.loads(data) pieChart.data = data pieChart.labels = [] labels = json.loads(labels.replace("'",'"')) for d in data: pieChart.labels.append(str(d)) # Create legend legend = Legend() legend.x = 380 legend.y = 60 legend.boxAnchor = 'se' legend.subCols[1].align = 'right' legend.colorNamePairs = [] len_data = len(data) for i in range(0,len_data): pieChart.slices[i].fillColor = colors[i] legend.colorNamePairs.append((colors[i],labels[i])) self.add(pieChart, "pie chart") self.add(legend, "legend")
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 create_pie(pie_data): pie_chart = Drawing(400, 200) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 100 pc.height = 100 pc.data = pie_data["data"] pc.labels = list(pie_data["label"][0]) pc.slices.strokeWidth=0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red pie_chart.add(pc) return pie_chart
def graphout_pie(data, labels, sizeOfDrawing): # data and labels are both lists of same size drawing = Drawing(sizeOfDrawing*inch, sizeOfDrawing*inch) pc = Pie() pc.x = .125*inch pc.y = .125*inch pc.width = (sizeOfDrawing-0.25)*inch pc.height = (sizeOfDrawing-0.25)*inch pc.data = data pc.labels = None pc.slices.strokeWidth = 0.5 # ensure pie chart and legend coloring matches for i in range(len(labels)): pc.slices[i].fillColor = colorList[i] drawing.add(pc) return drawing
def pie_graph(data, elements): drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = data pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing)
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 plpleg(i=None): from reportlab.lib.colors import pink, red, green pie = Pie() pie.x = 0 pie.y = 0 pie.pointerLabelMode='LeftAndRight' pie.slices.label_boxStrokeColor = red pie.simpleLabels = 0 pie.sameRadii = 1 pie.data = [1, 0.1, 1.7, 4.2,0,0] pie.labels = ['abcdef', 'b', 'c', 'd','e','fedcba'] pie.strokeWidth=1 pie.strokeColor=green pie.slices.label_pointer_piePad = 6 pie.width = 160 pie.direction = 'clockwise' pie.pointerLabelMode = 'LeftRight' return autoLegender(i,pie,pie.slices,None)
def piegraph(elements): drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.7 * inch))
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 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 _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 plpleg(i=None): from reportlab.lib.colors import pink, red, green pie = Pie() pie.x = 0 pie.y = 0 pie.pointerLabelMode = "LeftAndRight" pie.slices.label_boxStrokeColor = red pie.simpleLabels = 0 pie.sameRadii = 1 pie.data = [1, 0.1, 1.7, 4.2, 0, 0] pie.labels = ["abcdef", "b", "c", "d", "e", "fedcba"] pie.strokeWidth = 1 pie.strokeColor = green pie.slices.label_pointer_piePad = 6 pie.width = 160 pie.direction = "clockwise" pie.pointerLabelMode = "LeftRight" return autoLegender(i, pie, pie.slices, None)
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 _graphout(doc, category_names, data): drawing = Drawing(doc.width, 150) graph = Pie() graph.x = doc.width / 2 - 50 graph.y = 0 graph.height = 100 graph.width = 100 graph.labels = category_names graph.data = data graph.slices[0].fillColor = colors.darkcyan graph.slices[1].fillColor = colors.blueviolet graph.slices[2].fillColor = colors.blue graph.slices[3].fillColor = colors.cyan graph.slices[4].fillColor = colors.aquamarine graph.slices[5].fillColor = colors.cadetblue graph.slices[6].fillColor = colors.lightcoral drawing.add(graph) return drawing
def get_pdf_of_stats(data, title, config=config_default): canvas = Canvas("Results - " + title + ".pdf") trades = csv_to_trades(data, config) statss = all_trade_stats(trades, title) li = list(statss.split("\n")) start = 790 canvas.setFont('Times-Bold', 13) for i in li: canvas.drawString(70, start, i) start -= 15 # create the pie chart d = Drawing() pie = Pie() pie.x = 100 pie.y = 50 win_no = len(trade_filter(trades, True)) loss_no = len(trade_filter(trades, False)) total = float(win_no + loss_no) pie_data = [ np.round(100 * win_no / float(total)), np.round(100 * loss_no / float(total)) ] if total > 0 else [0, 0] pie.labels = ['Profiting', 'Losing'] pie.slices.strokeWidth = 0.5 pie.data = pie_data d.add(pie) renderPDF.draw(d, canvas, 300, 400, showBoundary=False) # create the bar chart d2 = Drawing() bar = VerticalBarChart() dataa = get_list(trades, 'profit') d2.add(bar, '') dataaa = [[x] for x in dataa] if len(dataaa) > 0: bar.data = dataaa for i in range(len(dataaa)): bar.bars[( i, 0 )].fillColor = colors.green if dataaa[i][0] > 0 else colors.red renderPDF.draw(d2, canvas, 300, 650, showBoundary=False) canvas.save()
def makePieChart(self, context, width, height, data, backColors): content=[] drawing = Drawing(width, height) pie=Pie() pie.data = data pie.x = 0 pie.y = 0 pie.width = width pie.height = height if len(data) == len(backColors): for i in range(len(data)) : pie.slices[i].fillColor = colors.HexColor(backColors[i]) drawing.add(pie) content.append( drawing ) return content
def generate(filename, title, additional_info, table_data, data, labels): 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) report_pie = Pie(width=3 * 30, height=3 * 30) empty_line = Spacer(1, 20) report_pie.data = data report_pie.labels = labels report_chart = Drawing() report_chart.add(report_pie) report.build([ report_title, empty_line, report_info, empty_line, report_table, report_chart ])
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 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 report_pdf(request): feedbacks = Feedback.objects.all() ## import pygraphviz as P ## A=P.AGraph() # init empty graph ## # set some default node attributes ## A.node_attr['style']='filled' ## A.node_attr['shape']='circle' ## # Add edges (and nodes) ## A.add_edge(1,2) ## A.add_edge(2,3) ## A.add_edge(1,3) ## A.layout() # layout with default (neato) ## png=A.draw(format='png') # draw png ## return HttpResponse(png, mimetype='image/png') pdf_data = open('cfback/feed.pdf','rb').read() response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="feedback.pdf"' buffer = BytesIO() p = Drawing(400,200) ## p.add(String(300,175, "Feedbacks", textAnchor="middle")) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [enumerate([i.title[0]]) for i in feedbacks] pc.labels = [str(y.company) for y in feedbacks] p.add(pc) ## p.showPage() p.save() pdf = buffer.getvalue() buffer.close response.write(pdf) return render_to_response('cfback/feed_report.html', response)
chartCanvas = Drawing() chartCanvas.hAlign = 'CENTER' chart = SimpleTimeSeriesPlot() chart.height = 150 chart.width = 500 chart.lines[0].strokeColor = PCMYKColor(100,0,90,50,alpha=100) chart.lines.strokeWidth = 2 chart.lines[1].strokeColor = PCMYKColor(0,100,100,40,alpha=100) chart.xValueAxis.xLabelFormat = '{mm}/{YY}' chart.data = [[('20120101', 100), ('20120102', 100), ('20120103', 101), ('20120104', 101), ('20120105', 102), ('20120106', 101), ('20120107', 101), ('20120108', 101), ('20120109', 102), ('20120110', 103), ('20120111', 103), ('20120112', 104), ('20120113', 103), ('20120114', 103), ('20120115', 103), ('20120116', 103), ('20120117', 103), ('20120118', 105), ('20120119', 106), ('20120120', 106), ('20120121', 106), ('20120122', 106), ('20120123', 106), ('20120124', 107), ('20120125', 108), ('20120126', 107), ('20120127', 107), ('20120128', 107), ('20120129', 107), ('20120130', 107), ('20120131', 107), ('20120201', 109), ('20120202', 109), ('20120203', 111), ('20120204', 111), ('20120205', 111), ('20120206', 111), ('20120207', 111), ('20120208', 111), ('20120209', 110), ('20120210', 109), ('20120211', 109), ('20120212', 109), ('20120213', 110), ('20120214', 110), ('20120215', 109), ('20120216', 111), ('20120217', 111), ('20120218', 111), ('20120219', 111), ('20120220', 111), ('20120221', 111), ('20120222', 111), ('20120223', 112), ('20120224', 111), ('20120225', 111), ('20120226', 111), ('20120227', 111), ('20120228', 111), ('20120229', 110), ('20120301', 111), ('20120302', 109), ('20120303', 109), ('20120304', 109), ('20120305', 109), ('20120306', 106), ('20120307', 108), ('20120308', 109), ('20120309', 111), ('20120310', 111), ('20120311', 111), ('20120312', 110), ('20120313', 113), ('20120314', 112), ('20120315', 113), ('20120316', 112), ('20120317', 112), ('20120318', 112), ('20120319', 113), ('20120320', 112), ('20120321', 112), ('20120322', 110), ('20120323', 111), ('20120324', 111), ('20120325', 111), ('20120326', 113), ('20120327', 113), ('20120328', 112), ('20120329', 112), ('20120330', 112), ('20120331', 112), ('20120401', 112), ('20120402', 113), ('20120403', 112), ('20120404', 110), ('20120405', 110), ('20120406', 110), ('20120407', 110), ('20120408', 110), ('20120409', 108), ('20120410', 106), ('20120411', 107), ('20120412', 109), ('20120413', 107), ('20120414', 107), ('20120415', 107), ('20120416', 107), ('20120417', 109), ('20120418', 108), ('20120419', 108), ('20120420', 108), ('20120421', 108), ('20120422', 108), ('20120423', 106), ('20120424', 107), ('20120425', 109), ('20120426', 110), ('20120427', 111), ('20120428', 111), ('20120429', 111), ('20120430', 110), ('20120501', 110), ('20120502', 110), ('20120503', 108), ('20120504', 106), ('20120505', 106), ('20120506', 106), ('20120507', 106), ('20120508', 106), ('20120509', 105), ('20120510', 106), ('20120511', 105), ('20120512', 105), ('20120513', 105), ('20120514', 104), ('20120515', 103), ('20120516', 103), ('20120517', 101), ('20120518', 100), ('20120519', 100), ('20120520', 100), ('20120521', 102), ('20120522', 102), ('20120523', 102), ('20120524', 102), ('20120525', 102), ('20120526', 102), ('20120527', 102), ('20120528', 102), ('20120529', 104), ('20120530', 102), ('20120531', 101), ('20120601', 98), ('20120602', 98), ('20120603', 98), ('20120604', 98), ('20120605', 99), ('20120606', 102), ('20120607', 101), ('20120608', 102), ('20120609', 102), ('20120610', 102), ('20120611', 100), ('20120612', 101), ('20120613', 99), ('20120614', 100), ('20120615', 101), ('20120616', 101), ('20120617', 101), ('20120618', 102), ('20120619', 103), ('20120620', 103), ('20120621', 100), ('20120622', 101), ('20120623', 101), ('20120624', 101), ('20120625', 99), ('20120626', 99), ('20120627', 100), ('20120628', 100), ('20120629', 103), ('20120630', 103), ('20120701', 103), ('20120702', 104), ('20120703', 106), ('20120704', 106), ('20120705', 106), ('20120706', 104), ('20120707', 104), ('20120708', 104), ('20120709', 104), ('20120710', 102), ('20120711', 102), ('20120712', 102), ('20120713', 103), ('20120714', 103), ('20120715', 103), ('20120716', 102), ('20120717', 103), ('20120718', 104), ('20120719', 104), ('20120720', 102), ('20120721', 102), ('20120722', 102), ('20120723', 101), ('20120724', 99), ('20120725', 100), ('20120726', 101), ('20120727', 104), ('20120728', 104), ('20120729', 104), ('20120730', 103), ('20120731', 103), ('20120801', 101), ('20120802', 101), ('20120803', 103), ('20120804', 103), ('20120805', 103), ('20120806', 104), ('20120807', 105), ('20120808', 105), ('20120809', 106), ('20120810', 106), ('20120811', 106), ('20120812', 106), ('20120813', 105), ('20120814', 105), ('20120815', 106), ('20120816', 107), ('20120817', 108), ('20120818', 108), ('20120819', 108), ('20120820', 107), ('20120821', 107), ('20120822', 107), ('20120823', 106), ('20120824', 106), ('20120825', 106), ('20120826', 106), ('20120827', 106), ('20120828', 107), ('20120829', 107), ('20120830', 106), ('20120831', 106), ('20120901', 106), ('20120902', 106), ('20120903', 106), ('20120904', 107), ('20120905', 107), ('20120906', 110), ('20120907', 110), ('20120908', 110), ('20120909', 110), ('20120910', 110), ('20120911', 110), ('20120912', 111), ('20120913', 112), ('20120914', 114), ('20120915', 114), ('20120916', 114), ('20120917', 113), ('20120918', 112), ('20120919', 112), ('20120920', 111), ('20120921', 111), ('20120922', 111), ('20120923', 111), ('20120924', 111), ('20120925', 109), ('20120926', 108), ('20120927', 110), ('20120928', 109), ('20120929', 109), ('20120930', 109), ('20121001', 109), ('20121002', 109), ('20121003', 109), ('20121004', 110), ('20121005', 110), ('20121006', 110), ('20121007', 110), ('20121008', 109), ('20121009', 108), ('20121010', 108), ('20121011', 108), ('20121012', 107), ('20121013', 107), ('20121014', 107), ('20121015', 108), ('20121016', 109), ('20121017', 110), ('20121018', 110), ('20121019', 108), ('20121020', 108), ('20121021', 108), ('20121022', 108), ('20121023', 107), ('20121024', 107), ('20121025', 107), ('20121026', 107), ('20121027', 107), ('20121028', 107), ('20121029', 107), ('20121030', 107), ('20121031', 109), ('20121101', 111), ('20121102', 109), ('20121103', 109), ('20121104', 109), ('20121105', 110), ('20121106', 111), ('20121107', 108), ('20121108', 107), ('20121109', 107), ('20121110', 107), ('20121111', 107), ('20121112', 107), ('20121113', 106), ('20121114', 104), ('20121115', 104), ('20121116', 105), ('20121117', 105), ('20121118', 105), ('20121119', 107), ('20121120', 107), ('20121121', 108), ('20121122', 108), ('20121123', 109), ('20121124', 109), ('20121125', 109), ('20121126', 109), ('20121127', 109), ('20121128', 109), ('20121129', 110), ('20121130', 110), ('20121201', 110), ('20121202', 110), ('20121203', 110), ('20121204', 110), ('20121205', 110), ('20121206', 110), ('20121207', 110), ('20121208', 110), ('20121209', 110), ('20121210', 111), ('20121211', 112), ('20121212', 112), ('20121213', 111), ('20121214', 111), ('20121215', 111), ('20121216', 111), ('20121217', 112), ('20121218', 114), ('20121219', 114), ('20121220', 114), ('20121221', 113), ('20121222', 113), ('20121223', 113), ('20121224', 113), ('20121225', 113), ('20121226', 112), ('20121227', 112), ('20121228', 112), ('20121229', 112), ('20121230', 112), ('20121231', 114)], [('20120101', 100), ('20120102', 100), ('20120103', 101), ('20120104', 100), ('20120105', 101), ('20120106', 101), ('20120107', 101), ('20120108', 101), ('20120109', 101), ('20120110', 103), ('20120111', 103), ('20120112', 104), ('20120113', 103), ('20120114', 103), ('20120115', 103), ('20120116', 103), ('20120117', 103), ('20120118', 105), ('20120119', 105), ('20120120', 105), ('20120121', 105), ('20120122', 105), ('20120123', 105), ('20120124', 106), ('20120125', 107), ('20120126', 107), ('20120127', 107), ('20120128', 107), ('20120129', 107), ('20120130', 107), ('20120131', 107), ('20120201', 109), ('20120202', 109), ('20120203', 112), ('20120204', 112), ('20120205', 112), ('20120206', 111), ('20120207', 111), ('20120208', 111), ('20120209', 111), ('20120210', 109), ('20120211', 109), ('20120212', 109), ('20120213', 111), ('20120214', 110), ('20120215', 109), ('20120216', 112), ('20120217', 111), ('20120218', 111), ('20120219', 111), ('20120220', 111), ('20120221', 111), ('20120222', 110), ('20120223', 112), ('20120224', 111), ('20120225', 111), ('20120226', 111), ('20120227', 111), ('20120228', 111), ('20120229', 109), ('20120301', 110), ('20120302', 108), ('20120303', 108), ('20120304', 108), ('20120305', 108), ('20120306', 106), ('20120307', 107), ('20120308', 109), ('20120309', 110), ('20120310', 110), ('20120311', 110), ('20120312', 110), ('20120313', 112), ('20120314', 111), ('20120315', 112), ('20120316', 112), ('20120317', 112), ('20120318', 112), ('20120319', 113), ('20120320', 112), ('20120321', 112), ('20120322', 111), ('20120323', 112), ('20120324', 112), ('20120325', 112), ('20120326', 114), ('20120327', 113), ('20120328', 112), ('20120329', 112), ('20120330', 112), ('20120331', 112), ('20120401', 112), ('20120402', 113), ('20120403', 113), ('20120404', 111), ('20120405', 110), ('20120406', 110), ('20120407', 110), ('20120408', 110), ('20120409', 108), ('20120410', 106), ('20120411', 107), ('20120412', 109), ('20120413', 107), ('20120414', 107), ('20120415', 107), ('20120416', 108), ('20120417', 109), ('20120418', 108), ('20120419', 108), ('20120420', 108), ('20120421', 108), ('20120422', 108), ('20120423', 107), ('20120424', 108), ('20120425', 110), ('20120426', 110), ('20120427', 111), ('20120428', 111), ('20120429', 111), ('20120430', 110), ('20120501', 110), ('20120502', 110), ('20120503', 109), ('20120504', 107), ('20120505', 107), ('20120506', 107), ('20120507', 107), ('20120508', 107), ('20120509', 106), ('20120510', 107), ('20120511', 107), ('20120512', 107), ('20120513', 107), ('20120514', 105), ('20120515', 105), ('20120516', 104), ('20120517', 102), ('20120518', 101), ('20120519', 101), ('20120520', 101), ('20120521', 103), ('20120522', 103), ('20120523', 103), ('20120524', 103), ('20120525', 103), ('20120526', 103), ('20120527', 103), ('20120528', 103), ('20120529', 105), ('20120530', 103), ('20120531', 103), ('20120601', 100), ('20120602', 100), ('20120603', 100), ('20120604', 100), ('20120605', 101), ('20120606', 103), ('20120607', 103), ('20120608', 104), ('20120609', 104), ('20120610', 104), ('20120611', 101), ('20120612', 103), ('20120613', 102), ('20120614', 103), ('20120615', 104), ('20120616', 104), ('20120617', 104), ('20120618', 104), ('20120619', 106), ('20120620', 106), ('20120621', 103), ('20120622', 105), ('20120623', 105), ('20120624', 105), ('20120625', 103), ('20120626', 103), ('20120627', 105), ('20120628', 105), ('20120629', 108), ('20120630', 108), ('20120701', 108), ('20120702', 109), ('20120703', 111), ('20120704', 111), ('20120705', 111), ('20120706', 109), ('20120707', 109), ('20120708', 109), ('20120709', 109), ('20120710', 108), ('20120711', 107), ('20120712', 107), ('20120713', 108), ('20120714', 108), ('20120715', 108), ('20120716', 108), ('20120717', 108), ('20120718', 109), ('20120719', 109), ('20120720', 107), ('20120721', 107), ('20120722', 107), ('20120723', 105), ('20120724', 104), ('20120725', 104), ('20120726', 105), ('20120727', 108), ('20120728', 108), ('20120729', 108), ('20120730', 107), ('20120731', 107), ('20120801', 104), ('20120802', 104), ('20120803', 107), ('20120804', 107), ('20120805', 107), ('20120806', 108), ('20120807', 109), ('20120808', 108), ('20120809', 109), ('20120810', 109), ('20120811', 109), ('20120812', 109), ('20120813', 108), ('20120814', 108), ('20120815', 109), ('20120816', 110), ('20120817', 111), ('20120818', 111), ('20120819', 111), ('20120820', 111), ('20120821', 110), ('20120822', 110), ('20120823', 109), ('20120824', 110), ('20120825', 110), ('20120826', 110), ('20120827', 110), ('20120828', 110), ('20120829', 111), ('20120830', 110), ('20120831', 110), ('20120901', 110), ('20120902', 110), ('20120903', 110), ('20120904', 111), ('20120905', 111), ('20120906', 114), ('20120907', 114), ('20120908', 114), ('20120909', 114), ('20120910', 114), ('20120911', 114), ('20120912', 115), ('20120913', 116), ('20120914', 117), ('20120915', 117), ('20120916', 117), ('20120917', 117), ('20120918', 116), ('20120919', 116), ('20120920', 116), ('20120921', 116), ('20120922', 116), ('20120923', 116), ('20120924', 116), ('20120925', 114), ('20120926', 113), ('20120927', 115), ('20120928', 114), ('20120929', 114), ('20120930', 114), ('20121001', 114), ('20121002', 114), ('20121003', 114), ('20121004', 115), ('20121005', 114), ('20121006', 114), ('20121007', 114), ('20121008', 114), ('20121009', 112), ('20121010', 112), ('20121011', 113), ('20121012', 112), ('20121013', 112), ('20121014', 112), ('20121015', 113), ('20121016', 113), ('20121017', 114), ('20121018', 114), ('20121019', 112), ('20121020', 112), ('20121021', 112), ('20121022', 111), ('20121023', 111), ('20121024', 111), ('20121025', 111), ('20121026', 110), ('20121027', 110), ('20121028', 110), ('20121029', 110), ('20121030', 110), ('20121031', 111), ('20121101', 113), ('20121102', 111), ('20121103', 111), ('20121104', 111), ('20121105', 111), ('20121106', 112), ('20121107', 109), ('20121108', 108), ('20121109', 108), ('20121110', 108), ('20121111', 108), ('20121112', 108), ('20121113', 107), ('20121114', 105), ('20121115', 105), ('20121116', 106), ('20121117', 106), ('20121118', 106), ('20121119', 108), ('20121120', 108), ('20121121', 109), ('20121122', 109), ('20121123', 110), ('20121124', 110), ('20121125', 110), ('20121126', 110), ('20121127', 110), ('20121128', 111), ('20121129', 112), ('20121130', 112), ('20121201', 112), ('20121202', 112), ('20121203', 112), ('20121204', 112), ('20121205', 112), ('20121206', 112), ('20121207', 112), ('20121208', 112), ('20121209', 112), ('20121210', 112), ('20121211', 114), ('20121212', 113), ('20121213', 112), ('20121214', 112), ('20121215', 112), ('20121216', 112), ('20121217', 114), ('20121218', 115), ('20121219', 116), ('20121220', 116), ('20121221', 116), ('20121222', 116), ('20121223', 116), ('20121224', 115), ('20121225', 115), ('20121226', 114), ('20121227', 114), ('20121228', 113), ('20121229', 113), ('20121230', 113), ('20121231', 116)]] chartCanvas.add(chart) renderPDF.draw(chartCanvas, c, 50, 400) pieChartCanvas = Drawing() pieChart = Pie() pieChart.data = [30.0, 21.0, 21.0, 14.0, 14.0] pieChart.slices[0].fillColor = PCMYKColor(100,0,90,50,alpha=85) pieChart.slices[1].fillColor = PCMYKColor(0,100,100,40,alpha=85) pieChart.slices[2].fillColor = PCMYKColor(100,60,0,50,alpha=85) pieChart.slices[3].fillColor = PCMYKColor(23,51,0,4,alpha=85) pieChart.slices[4].fillColor = PCMYKColor(66,13,0,22,alpha=85) pieChart.width = 100 pieChart.height = 100 pieChart.slices.popout = 5 pieChart.slices.strokeColor = PCMYKColor(0,0,0,0) pieChart.slices.strokeWidth = 0.5 pieChartCanvas.add(pieChart) renderPDF.draw(pieChartCanvas, c, 100, 100) pieChartLegendCanvas = Drawing() pieChartLegend = Legend()
def __per_account_statistic(self): for acc in self.accounts: p = PageBreak() p.drawOn(self.c, 0, 1000) self.c.showPage() self.l = 760 self.c.setFont('Courier', 14) self.c.drawString(30, 800, 'Cuenta: %s' % \ acc.name) header = ['Fecha', 'Tipo', 'Monto', 'Description'] data = [header] g_data = list() g_labe = list() total = 0 for tra in self.transactions: if tra.account == acc.name: if tra.t_type in ['expense', 'transfer']: tipo = self.__translate_type(tra.t_type) data.append([tra.date, tipo.upper(), '$%2.f' % tra.amount, tra.description]) total += tra.amount g_data.append(tra.amount) g_labe.append(tra.description.encode('utf-8')) data.append(['TOTAL', '', '$%.2f' % total, '']) if len(g_data) == 0 or len(g_labe) == 0: self.c.setFont('Courier', 12) self.c.drawString(30, 770, 'Sin movimientos negativos') continue from_title = 35 if len(data) != 2: self.l -= ((len(data) * len(data)) + len(data)) + from_title t = Table(data) t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black), ('BOX', (0,0), (-1,-1), 0.25, black), ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'), ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')), ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')), ('FONTSIZE', (0,0), (-1,0), 12), ('FONTSIZE', (0,1), (-1,-1), 8), ('FONTNAME', (0,1), (-1,-1), 'Courier'), ('BACKGROUND', (0,-1), (-1,-1), red), ('TEXTCOLOR', (0,-1), (-1,-1), white)])) t.wrapOn(self.c, 30, self.l) t.drawOn(self.c, 30, self.l) drawing = Drawing(200, 100) pie = Pie() pie.x = 30 pie.y = self.l - 300 pie.height = 200 pie.width = 200 pie.data = g_data pie.labels = g_labe pie.simpleLabels = 1 pie.slices.strokeWidth = 1 pie.slices.strokeColor = black pie.slices.label_visible = 0 pie.slices.popout = 1 #pie.labels = map(str, pie.data) legend = Legend() legend.x = 250 legend.y = self.l - 250 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'w' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = 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 n = len(pie.data) self.__setItems(n,pie.slices, 'fillColor',self.pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)] drawing.add(pie) drawing.add(legend) x, y = 0, 10 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
def generate_certificate(elements): styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catnames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catnames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.7 * inch)) styles = ParagraphStyle( name='Normal', fontName='Helvetica', fontSize=15, alignment=0, ) elements.append(Spacer(1, 0.5* inch)) i = Paragraph(str("Please click on black square to play the video."), styles) elements.append(i) elements.append(platypus.flowables.Macro('canvas.saveState()')) elements.append(platypus.flowables.Macro('canvas.linkURL("fun.mp4",(400,510,410,500),relative=0,thickness=10)')) elements.append(platypus.flowables.Macro('canvas.restoreState()')) return elements
def generate_certificate(elements): style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.red), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red), ('BOX', (0, 0), (-1, -1), 0.50, colors.green), ('BACKGROUND', (0, 0), (-1, -1), colors.blue), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = "RGB" styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) return elements
def __get_tags_statistics(self): monto_categorias = dict() for tra in self.transactions: if len(tra.tags) > 0: for tag in tra.tags: if tag in monto_categorias.keys(): monto_categorias[tag] += tra.amount else: monto_categorias[tag] = tra.amount labels = [lab.encode('utf-8') for lab in monto_categorias.keys()] data = monto_categorias.values() p = PageBreak() p.drawOn(self.c, 0, 1000) self.c.showPage() self.l = 600 self.c.setFont('Courier', 14) self.c.drawString(30, 800, 'Categorias') drawing = Drawing(200, 200) pie = Pie() pie.x = 30 pie.y = self.l - 130 pie.height = 300 pie.width = 300 pie.data = data pie.labels = labels pie.simpleLabels = 1 pie.slices.strokeWidth = 1 pie.slices.strokeColor = black pie.slices.label_visible = 0 legend = Legend() legend.x = 400 legend.y = self.l legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'w' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = 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 n = len(pie.data) self.__setItems(n,pie.slices, 'fillColor',self.pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)] drawing.add(pie) drawing.add(legend) x, y = 0, 10 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
# Hack to force a new paragraph before the todo() :-( disc("") from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f']
pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) """) from reportlab.graphics.charts.piecharts import Pie d = Drawing(200, 100) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 70 pc.height = 70 pc.data = [10,20,30,40,50,60] pc.labels = ['a','b','c','d','e','f'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) draw(d, 'A bare bones pie chart') disc(""" Properties are covered below.
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 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)