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 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 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 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 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 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 __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_pie(data=[], labels=[], use_colors=[], width=360,): '''更多属性请查询reportlab.graphics.charts.piecharts.WedgeProperties''' pie = Pie() pie.x = 60 # x,y饼图在框中的坐标 pie.y = 20 pie.slices.label_boxStrokeColor = colors.white #标签边框的颜色 pie.data = data # 饼图上的数据 pie.labels = labels # 数据的标签 pie.simpleLabels = 0 # 0 标签在标注线的右侧;1 在线上边 pie.sameRadii = 1 # 0 饼图是椭圆;1 饼图是圆形 pie.slices.strokeColor = colors.red # 圆饼的边界颜色 pie.strokeWidth=1 # 圆饼周围空白区域的宽度 pie.strokeColor= colors.white # 整体饼图边界的颜色 pie.slices.label_pointer_piePad = 10 # 圆饼和标签的距离 pie.slices.label_pointer_edgePad = 25 # 标签和外边框的距离 pie.width = width pie.direction = 'clockwise' pie.pointerLabelMode = 'LeftRight' # for i in range(len(labels)): # pie.slices[i].fontName = 'song' #设置中文 for i, col in enumerate(use_colors): pie.slices[i].fillColor = col return pie
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 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 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 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 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 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 simple_pie_chart_label_customization(): 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'] # enable label customization pie.simpleLabels = 0 # add some customization pie.slices[0].label_angle = 45 pie.slices[0].label_text = 'foobar' # normal pie properties 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_label_customization')
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 build_pdf(): fruit = {"elderberries": 1,"figs": 1,"apples": 2,"durians": 3,"bananas": 5,"cherries": 8,"grapes": 13} report = SimpleDocTemplate("/home/scottdavis/eclipse-workspace/module1/report.pdf") styles = getSampleStyleSheet() report_title = Paragraph("A Complete Inventory of My Fruit", styles["h1"]) table_data = [] for k, v in fruit.items(): table_data.append([k, v]) table_style = [('GRID', (0,0), (-1,-1), 1, colors.black)] report_table = Table(data=table_data, style=table_style, hAlign="LEFT") report_pie = Pie() #width=3*inch, height=3*inch report_pie.width = 180 report_pie.height = 180 report_pie.data = [] report_pie.labels = [] for fruit_name in sorted(fruit): report_pie.data.append(fruit[fruit_name]) report_pie.labels.append(fruit_name) report_chart = Drawing() report_chart.add(report_pie) report.build([report_title, report_table, report_chart])
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 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 = u'0 \xe4 b c d e f g h i'.split() 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 pc.slices[1].fontName = fontName 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 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 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 __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 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 __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 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 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 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 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 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 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 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 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_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 __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 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 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 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 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 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)
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"] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, "pie3") draw(d, "Some sample Pies")
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'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') draw(d, 'Some sample Pies')
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 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
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. The pie has a 'wedges' collection and we document wedge properties
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)
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 __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)