def legend_draw(self, labels, chart, **kwargs): legend = Legend() chart_type = kwargs['type'] # legend.fontName = 'FreeSans' legend.fontSize = 13 legend.strokeColor = None if 'x' in kwargs: legend.x = kwargs['x'] if 'y' in kwargs: legend.y = kwargs['y'] legend.alignment = 'right' if 'boxAnchor' in kwargs: legend.boxAnchor = kwargs['boxAnchor'] if 'columnMaximum' in kwargs: legend.columnMaximum = kwargs['columnMaximum'] # x-distance between neighbouring swatche\s legend.deltax = 0 lcolors = get_random_colors(10) if chart_type == 'line': lcolors = [colors.red, colors.blue] elif chart_type == 'pie': lcolors = [colors.darkgreen, colors.darkblue] + lcolors legend.colorNamePairs = list(zip(lcolors, labels)) for i, color in enumerate(lcolors): if chart_type == 'line': chart.lines[i].fillColor = color elif chart_type == 'pie': chart.slices[i].fillColor = color elif chart_type == 'bar': chart.bars[i].fillColor = color return legend
def draw_bar(bar_data=[], ax=[], items=[]): drawing = Drawing(500, 250) bc = VerticalBarChart() bc.x = 35 bc.y = 100 bc.height = 120 bc.width = 350 bc.data = bar_data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 20 bc.categoryAxis.categoryNames = ax # 图示 leg = Legend() leg.fontName = 'song' leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 465 leg.y = 220 leg.dxTextSpace = 10 leg.columnMaximum = 3 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing
def show_figure(data, y_max, x_category, legend_category): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 150 bc.width = 450 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = y_max # bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = len(data[0]) # bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = x_category drawing.add(bc) # add legend from here swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 190 swatches.deltax = 30 swatches.dxTextSpace = 10 swatches.columnMaximum = 1 color_list = (colors.red, colors.green, colors.blue, colors.pink, colors.yellow) items = [] for index, item in enumerate(legend_category): items.append((color_list[index], item)) swatches.colorNamePairs = items drawing.add(swatches, 'legend') return drawing
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 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 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 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 make_legend(self, drawing, chart): if not self.legend_labels: return # Get legend labels labels = self.get_legend_labels() # Legend object legend = Legend() legend.colorNamePairs = zip(self.colors[:len(labels)], labels) legend.columnMaximum = len(legend.colorNamePairs) legend.deltay = 5 legend.alignment = 'right' legend.x = drawing.width + 40 legend.y = drawing.height - (self.title and self.title.get('height', DEFAULT_TITLE_HEIGHT) or 0) # Sets legend extra attributes if legend_labels is a dictionary if isinstance(self.legend_labels, dict): for k,v in self.legend_labels.items(): if k != 'labels' and v: setattr(legend, k, v) drawing.add(legend) return legend
def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.lineLabelFormat = None self.chart.xLabel = 'X Axis' self.chart.y = 30 self.chart.yLabel = 'Y Axis' self.chart.yValueAxis.labelTextFormat = '%d' self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self,0,name='preview',validate=None,desc=None)
def __init__(self, width=400, height=200, data=[], labels=[], legends=[], *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.add(VerticalBarChart(), name='chart') self.add(Legend(), name='legend') self.chart.x = 15 self.chart.y = 15 self.chart.width = self.width - 20 self.chart.height = self.height - 40 self.chart.data = data self.chart.categoryAxis.categoryNames = labels self.chart.categoryAxis.labels.boxAnchor = 'ne' self.chart.categoryAxis.labels.angle = 30 for i in range(len(data)): self.chart.bars[i].fillColor = color_list[i] self.legend.alignment = 'right' self.legend.x = self.width self.legend.y = self.height - self.height / 4 self.legend.dx = 8 self.legend.dy = 8 self.legend.deltay = 10 self.legend.dxTextSpace = 3 self.legend.columnMaximum = 10 self.legend.colorNamePairs = [(color_list[i], legends[i]) for i in range(len(legends))]
def insert_legend(self): """ Insert legend into graphic """ self._add(self, Legend(), name='legend') self.legend.deltay = 8 self.legend.fontName = 'Helvetica' self.legend.fontSize = 5 self.legend.strokeWidth = 0.5 self.legend.strokeColor = PCMYKColor(0, 0, 0, 100) self.legend.alignment = 'right' self.legend.columnMaximum = 3 self.legend.boxAnchor = 'sw' self.legend.y = 75 self.legend.x = 24 self.legend.dx = 8 self.legend.dy = 5 self.legend.dxTextSpace = 5 self.legend.deltax = 0 self.legend.colorNamePairs = Auto(obj=self.chart) self.chart.bars[0].fillColor = self.random_color() self.chart.bars[1].fillColor = self.random_color() self.chart.bars[2].fillColor = self.random_color() self.chart.bars[3].fillColor = self.random_color()
def SetLegend(self, colorsAndLabels, x=None, y=None, dxChartSpace=36, legendAlign='right', fontname="Helvetica-Bold", fontsize=10, dxTextSpace=10, dy=10, dx=10, dySpace=15, maxCols=2): self._add(self, Legend(), name='Legend', validate=None, desc="The pie legend object") self.Legend.fontName = fontname self.Legend.fontSize = fontsize self.Legend.dxTextSpace = dxTextSpace self.Legend.dy = dy self.Legend.dx = dx self.Legend.deltay = dySpace self.Legend.alignment = legendAlign self.Legend.columnMaximum = maxCols self.Legend.colorNamePairs = colorsAndLabels if None in (x, y): x = self.chart.x + self.chart.width + dxChartSpace legendY1, legendY2 = self.Legend.getBounds()[1::2] legendH = abs(legendY2 - legendY1) figH = self.height y = figH / 2 + legendH / 2 # drawing is relative to document template flowable space --> self.x,self.y=0,0 (although these are real attributes) self.Legend.x = x self.Legend.y = y
def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) fontSize = 8 fontName = 'Helvetica' #pie self._add(self, Pie(), name='pie', validate=None, desc=None) self.pie.strokeWidth = 1 self.pie.slices.strokeColor = PCMYKColor(0, 0, 0, 0) self.pie.slices.strokeWidth = 1 #legend self._add(self, Legend(), name='legend', validate=None, desc=None) self.legend.columnMaximum = 99 self.legend.alignment = 'right' self.legend.dx = 6 self.legend.dy = 6 self.legend.dxTextSpace = 5 self.legend.deltay = 10 self.legend.strokeWidth = 0 self.legend.subCols[0].minWidth = 75 self.legend.subCols[0].align = 'left' self.legend.subCols[1].minWidth = 25 self.legend.subCols[1].align = 'right' # sample data colors = [ PCMYKColor(100, 67, 0, 23, alpha=100), PCMYKColor(70, 46, 0, 16, alpha=100), PCMYKColor(50, 33, 0, 11, alpha=100), PCMYKColor(30, 20, 0, 7, alpha=100), PCMYKColor(20, 13, 0, 4, alpha=100), PCMYKColor(10, 7, 0, 3, alpha=100), PCMYKColor(0, 0, 0, 100, alpha=100), PCMYKColor(0, 0, 0, 70, alpha=100), PCMYKColor(0, 0, 0, 50, alpha=100), PCMYKColor(0, 0, 0, 30, alpha=100), PCMYKColor(0, 0, 0, 20, alpha=100), PCMYKColor(0, 0, 0, 10, alpha=100) ] self.pie.data = [56.0, 12.199999999999999, 28.5, 3.3999999999999999] for i in range(len(self.pie.data)): self.pie.slices[i].fillColor = colors[i] self.height = 200 self.legend.boxAnchor = 'c' self.legend.y = 100 self.pie.strokeColor = PCMYKColor(0, 0, 0, 0, alpha=100) self.pie.slices[1].fillColor = PCMYKColor(100, 60, 0, 50, alpha=100) self.pie.slices[2].fillColor = PCMYKColor(0, 100, 100, 40, alpha=100) self.pie.slices[3].fillColor = PCMYKColor(66, 13, 0, 22, alpha=100) self.pie.slices[0].fillColor = PCMYKColor(100, 0, 90, 50, alpha=100) self.legend.colorNamePairs = [ (PCMYKColor(100, 0, 90, 50, alpha=100), ('BP', '56.0%')), (PCMYKColor(100, 60, 0, 50, alpha=100), ('BT', '12.2%')), (PCMYKColor(0, 100, 100, 40, alpha=100), ('Tesco', '28.5%')), (PCMYKColor(66, 13, 0, 22, alpha=100), ('Persimmon', '3.4%')) ] self.width = 400 self.legend.x = 350 self.pie.width = 150 self.pie.height = 150 self.pie.y = 25 self.pie.x = 25
def __init__(self, pie_data, width=400, height=200): apply(Drawing.__init__, (self, width, height)) self._add(self, Pie(), name='chart', validate=None, desc=None) self.chart.x = 20 self.chart.y = (self.height - self.chart.height) / 2 self.chart.slices.strokeWidth = 1 self.chart.slices.popout = 1 self.chart.direction = 'clockwise' self.chart.width = self.chart.height self.chart.startAngle = 90 self.chart.slices[0].popout = 10 self._add(self, Legend(), name='legend', validate=None, desc=None) self.legend.x = width - 20 self.legend.y = 0 self.legend.boxAnchor = 'se' self.legend.subCols[1].align = 'right' # these data can be read from external sources data = [] categories = [] for d in pie_data.keys(): categories.append(d) data.append(pie_data.get(d, 0)) #data = (9, 7, 6, 4, 2.5, 1.0) #categories = ('A','B','C','D','E','F',) colors = [ PCMYKColor(0, 1, 550, x) for x in (1030, 2080, 3060, 440, 4520, 2225) ] self.chart.data = data self.chart.labels = map(str, self.chart.data) self.legend.colorNamePairs = zip(colors, categories) for i, color in enumerate(colors): self.chart.slices[i].fillColor = color
def __init__(self, width=400, height=200, data=[], labels=[], legends=[], *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.add(Pie(), name='chart') self.add(Legend(), name='legend') self.chart.x = self.width / 4 self.chart.y = 15 self.chart.width = self.width - 150 self.chart.height = self.height - 40 self.chart.data = data for i in range(len(data)): self.chart.slices[i].fillColor = color_list[i] self.legend.alignment = 'right' self.legend.x = self.width - 20 self.legend.y = self.height - self.height / 4 self.legend.dx = 8 self.legend.dy = 8 self.legend.deltay = 10 self.legend.dxTextSpace = 3 self.legend.columnMaximum = 10 self.legend.colorNamePairs = [(color_list[i], legends[i]) for i in range(len(legends))]
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, width=155, height=138, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) fontName = 'Helvetica' fontSize = 6 self._add(self, Pie(), name='pie', validate=None, desc=None) self._add(self, Legend(), name='legend', validate=None, desc=None) colors = [ PCMYKColor(40, 0, 7, 40, alpha=100), PCMYKColor(0, 12, 9, 87, alpha=100), PCMYKColor(30, 0, 6, 33, alpha=100), PCMYKColor(0, 4, 4, 69, alpha=100), PCMYKColor(21, 0, 5, 25, alpha=100), PCMYKColor(0, 2, 2, 52, alpha=100) ] self.pie.data = [ 30.600000000000001, 8.5, 39.299999999999997, 7.7000000000000002, 11.6, 2.2000000000000002 ] self.pie.sameRadii = 1 for i in range(len(self.pie.data)): self.pie.slices[i].fillColor = colors[i] self.pie.slices.strokeColor = PCMYKColor(0, 0, 0, 0) self.pie.slices.strokeWidth = 0.5 self.legend.alignment = 'right' self.legend.fontName = fontName self.legend.fontSize = fontSize self.legend.dx = 6.5 self.legend.dy = 6.5 self.legend.yGap = 0 self.legend.deltax = 10 self.legend.deltay = 10 self.legend.strokeColor = PCMYKColor(0, 0, 0, 0) self.legend.strokeWidth = 0 self.legend.columnMaximum = 4 self.width = 400 self.height = 200 self.legend.y = 100 self.legend.boxAnchor = 'c' self.legend.x = 325 self.pie.x = 25 self.pie.y = 25 self.pie.height = 150 self.pie.width = 150 self.pie.slices[0].fillColor = PCMYKColor(23, 51, 0, 4, alpha=100) self.pie.slices[1].fillColor = PCMYKColor(0, 100, 100, 40, alpha=100) self.pie.slices[5].fillColor = PCMYKColor(0, 61, 22, 25, alpha=100) self.pie.slices[2].fillColor = PCMYKColor(100, 60, 0, 50, alpha=100) self.pie.slices[3].fillColor = PCMYKColor(100, 0, 90, 50, alpha=100) self.pie.slices[4].fillColor = PCMYKColor(66, 13, 0, 22, alpha=100) self.legend.colorNamePairs = [ (PCMYKColor(23, 51, 0, 4, alpha=100), u'Europe: 30.6'), (PCMYKColor(0, 100, 100, 40, alpha=100), u'Japan: 8.5'), (PCMYKColor(100, 60, 0, 50, alpha=100), u'US/Canada: 39.3'), (PCMYKColor(100, 0, 90, 50, alpha=100), u'Asia ex Japan: 7.7'), (PCMYKColor(66, 13, 0, 22, alpha=100), u'Latin\nAmerica/Other: 11.6'), (PCMYKColor(0, 61, 22, 25, alpha=100), u'Australia/New\nZealand: 2.2') ]
def __init__(self, labels, data, width=400, height=200, *args, **kw): pdf_chart_colors = [ HexColor("#0000e5"), HexColor("#1f1feb"), HexColor("#5757f0"), HexColor("#8f8ff5"), HexColor("#c7c7fa"), HexColor("#f5c2c2"), HexColor("#eb8585"), HexColor("#e04747"), HexColor("#d60a0a"), HexColor("#cc0000"), HexColor("#ff0000"), ] apply(Drawing.__init__, (self, width, height) + args, kw) # adding a pie chart to the drawing self._add(self, Pie(), name='pie', validate=None, desc=None) self.pie.width = 150 self.pie.height = self.pie.width self.pie.x = 20 self.pie.y = (height - self.pie.height) / 2 # self.pie.data = [26.90, 13.30, 11.10, 9.40, 8.50, 7.80, 7.00, 6.20, 8.80, 1.00] self.pie.data = data # self.pie.labels = ['Financials', 'Energy', 'Health Care', 'Telecoms', 'Consumer', 'Consumer 2', 'Industrials', # 'Materials', 'Other', 'Liquid Assets'] self.pie.labels = labels self.pie.simpleLabels = 1 self.pie.slices.label_visible = 0 self.pie.slices.fontColor = None self.pie.slices.strokeColor = white self.pie.slices.strokeWidth = 1 # adding legend self._add(self, Legend(), name='legend', validate=None, desc=None) self.legend.x = 200 self.legend.y = height / 2 self.legend.dx = 8 self.legend.dy = 8 self.legend.fontName = 'Helvetica' self.legend.fontSize = 7 self.legend.boxAnchor = 'w' self.legend.columnMaximum = 10 self.legend.strokeWidth = 1 self.legend.strokeColor = black self.legend.deltax = 75 self.legend.deltay = 10 self.legend.autoXPadding = 5 self.legend.yGap = 0 self.legend.dxTextSpace = 5 self.legend.alignment = 'right' self.legend.dividerLines = 1 | 2 | 4 self.legend.dividerOffsY = 4.5 self.legend.subCols.rpad = 30 n = len(self.pie.data) self.set_items(n, self.pie.slices, 'fillColor', pdf_chart_colors) self.legend.colorNamePairs = [(self.pie.slices[i].fillColor, (self.pie.labels[i][0:20], '%0.2f' % self.pie.data[i])) for i in xrange(n)]
def __init__(self, width, height, x, y, categoryXlables, datas, categoryYlables, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) # font fontName = 'msyh' # chart # self._add(self,VerticalBarChart(),name='chart',validate=None,desc=None) # self.chart.width = width-x # self.chart.height = height-15 # # chart bars # self.chart.bars.strokeColor = None # self.chart.bars.strokeWidth = 0 # self.chart.barSpacing = 4 # self.chart.barLabels.fontName = fontName # self.chart.barLabels.fontSize = 5 # self.chart.data = datas # self.chart.categoryAxis.categoryNames=categoryXlables # # categoy axis # # self.chart.categoryAxis.labelAxisMode='low' # self.chart.categoryAxis.labels.boxAnchor = 'ne' # self.chart.categoryAxis.labels.dy = 5 # self.chart.categoryAxis.labels.fillColor = PCMYKColor(0,0,0,100) # self.chart.categoryAxis.labels.fontName = fontName # self.chart.categoryAxis.labels.fontSize = 5 # # self.chart.categoryAxis.labels.angle=25 # self.chart.categoryAxis.labels.textAnchor='start' # self.chart.categoryAxis.strokeWidth = 0 # self.chart.categoryAxis.style = 'stacked' # # value axis # self.chart.valueAxis.labels.fontName = fontName # self.chart.valueAxis.labels.fontSize = 8 # self.chart.valueAxis.strokeWidth = 0 # self.chart.valueAxis.visibleGrid = True # self.chart.valueAxis.visibleTicks = True # self.chart.valueAxis.visibleAxis = True # legend self._add(self, Legend(), name='legend', validate=None, desc=None) self.legend.alignment = 'right' self.legend.boxAnchor = 'sw' self.legend.fontSize = 5 self.legend.fontName = fontName self.legend.strokeColor = None self.legend.strokeWidth = 0 self.legend.subCols.minWidth = 55 self.legend.columnMaximum = 1 self.legend.deltay = 1 self.legend.colorNamePairs = zip( task_type_color[0:len(categoryYlables)], categoryYlables) # self.legend.colorNamePairs = Auto(obj=self.chart) # for i in range(len(categoryYlables)): # self.chart.bars[i].name = categoryYlables[i] # self.chart.bars[i].fillColor = task_type_color[i] # self.chart.x = x # self.chart.y = y self.legend.x = x
def __init__(self, drawing=None, title=None, data=None, x=25, y=30, width=490, height=70): if len(data) > 1: width -= 65 bars = VerticalBarChart() bars.x = x bars.y = y bars.data = [[value for (_, value) in category] for category in data] bars.width = width bars.height = height bars.valueAxis.forceZero = 1 bars.valueAxis.labels.fontName = 'Lato' bars.valueAxis.labels.fontSize = 9 bars.valueAxis.strokeColor = white bars.valueAxis.visibleGrid = 1 #bars.bars[0].fillColor = toColor(my_color_func()) bars.bars.strokeColor = white bars.categoryAxis.categoryNames = [key for (key, _) in data[0]] bars.categoryAxis.tickUp = 0 bars.categoryAxis.tickDown = 0 bars.categoryAxis.labels.fontName = 'Lato' bars.categoryAxis.labels.fontSize = 9 legend = Legend() legend.y = 70 legend.x = 457 legend.strokeColor = white legend.alignment = 'right' legend.fontName = 'Lato' legend.fontSize = 9 colors = map(toColor, get_n_random_colors(len(data))) for (i, color) in enumerate(colors): bars.bars[i].fillColor = color if len(data) > 1: legend_data = (title, 'Benchmark') legend.colorNamePairs = zip(colors, legend_data) drawing.add(legend) drawing.add(bars)
def add_trends_new_resolved_findings_chart(): drawing = Drawing(200, 200) data, month = get_new_resolved_trends() max_val_new_findings = max(data[0]) max_val_resolved_findings = max(data[1]) maxVal = max(max_val_new_findings, max_val_resolved_findings) if (maxVal > 1000): multiplier = 1000 step = 4 * multiplier else: multiplier = 100 step = 4 * multiplier value_step = int(ceil(maxVal / step)) * multiplier if (value_step < 10): value_step = 1 bar = VerticalBarChart() bar.x = 25 bar.y = -35 bar.height = 100 bar.width = doc.width bar.barWidth = 2 bar.data = data bar.valueAxis.valueMin = 0 bar.valueAxis.valueMax = int( maxVal * 2) ## graph displa twice as much as max violation bar.valueAxis.valueStep = value_step ## Convert to neartest step bar.categoryAxis.categoryNames = month bar.bars[0].strokeColor = None bar.bars[1].strokeColor = None bar.bars[0].fillColor = HexColor("#E57300") bar.bars[1].fillColor = HexColor("#408F00") chartLabel = Label() chartLabel.setText("Trends - New Findings") chartLabel.fontSize = 10 chartLabel.fillColor = HexColor("#737373") chartLabel.fontName = 'Helvetica-Bold' chartLabel.dx = 250 chartLabel.dy = 90 legend = Legend() legend.alignment = 'right' legend.colorNamePairs = [[HexColor("#E57300"), "New Findings"], [HexColor("#408F00"), "Resolved Findings"]] legend.columnMaximum = 2 legend.x = 400 legend.y = 120 drawing.add(legend) drawing.add(chartLabel) drawing.add(bar) fields.append(drawing)
def __init__(self, width=200, height=150, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self._add(self, SpiderChart(), name='chart', validate=None, desc="The main chart") self.chart.width = 90 self.chart.height = 90 self.chart.x = 45 self.chart.y = 25 self.chart.strands[0].fillColor = color01 self.chart.strands[1].fillColor = color02 self.chart.strands[2].fillColor = color03 self.chart.strands[3].fillColor = color04 self.chart.strands[4].fillColor = color05 self.chart.strands[5].fillColor = color06 self.chart.strands[6].fillColor = color07 self.chart.strands[7].fillColor = color08 self.chart.strands[8].fillColor = color09 self.chart.strands[9].fillColor = color10 self.chart.strandLabels.fontName = 'Helvetica' self.chart.strandLabels.fontSize = 6 self.chart.fillColor = backgroundGrey self.chart.data = [(125, 180, 200), (100, 150, 180)] self.chart.labels = ['North', 'South', 'Central'] self._add(self, Label(), name='Title', validate=None, desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor = 'middle' self._add(self, Legend(), name='Legend', validate=None, desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment = 'right' self._add(self, 0, name='preview', validate=None, desc=None)
def add_legend(draw_obj, chart, data): legend = Legend() legend.fontName = 'SimSun' legend.alignment = 'right' legend.x = 10 legend.y = 70 legend.colorNamePairs = Auto(obj=chart) draw_obj.add(legend)
def myBarLegend(drawing, name1, name2): "Add sample swatches to a diagram." d = drawing or Drawing(400, 200) swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 160 swatches.deltax = 60 swatches.dxTextSpace = 10 swatches.columnMaximum = 4 items = [(colors.red, name1), (colors.lightblue, name2)] swatches.colorNamePairs = items d.add(swatches, 'legend') return d
def createReadsHistogram(self): ''' Routine to create histogram of numbers of 'reads' for given years ''' # The vertical bar chart will get added to the 'drawing' object drawing = Drawing(400, 200) # Now we can start constructing the vertical bar chart lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 # Record the years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['reads histogram'].keys()))) # This list will hold the data points for the histogram lc.data = [] # Record the counts of both reads of refereed and non-refereed papers refereed = [] non_refereed = [] # The maximum number of reads will be used to scale the y axis max_reads = 0 # Take only the first two values of each value string in the histogram data # The first is for 'all' papers, the second for the 'refereed' papers for year in years: values = map(lambda a: int(a),self.data['reads histogram'][str(year)].split(':')[:2]) max_reads = max(max_reads,max(values)) refereed.append(values[1]) non_refereed.append(values[0]-values[1]) lc.data.append(refereed) lc.data.append(non_refereed) # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lc.categoryAxis.labels.dx = -6 lc.categoryAxis.labels.dy = -6 # and rotate the labels by 90 degrees lc.categoryAxis.labels.angle = 90 # Define the value step and maximum for the y axis lc.valueAxis.valueMax = int(math.ceil(float(max_reads)/10.0))*10 lc.valueAxis.valueStep = max(int(math.floor(float(max_reads)/10.0)),1) lc.valueAxis.valueMin = 0 # The label names are the access years lc.categoryAxis.categoryNames = map(lambda a: str(a), years) # Now add the histogram to the 'drawing' object drawing.add(lc) # Add a legend to the histogram so that we now which color means what legend = Legend() legend.alignment = 'right' legend.x = 380 legend.y = 160 legend.deltax = 60 legend.dxTextSpace = 10 items = [(colors.red, 'refereed'), (colors.green, 'non-refereed')] legend.colorNamePairs = items drawing.add(legend, 'legend') # Finally add a title to the histogram drawing.add(String(200,190,"reads histogram", textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self.chart.startAngle = -90 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.Legend.columnMaximum = 10 self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 20 self.background.y = 20 self.chart.slices.popout = 5 self.background.height = 110 self.background.width = 110 self._add(self,0,name='preview',validate=None,desc=None)
def myBarLegend(drawing, name1, name2): "Add sample swatches to a diagram." d = drawing or Drawing(400, 200) swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 160 swatches.deltax = 60 swatches.dxTextSpace = 10 swatches.columnMaximum = 4 items = [(colors.blue, name1), (colors.lightblue, name2)] swatches.colorNamePairs = items d.add(swatches, 'legend') return d
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 add_legend(draw_obj, chart, data, doc): legend = Legend() legend.alignment = 'right' legend.x = 100 legend.y = -110 legend.colorNamePairs = Auto(obj=chart) draw_obj.add(legend)
def sample3(drawing=None): "Add sample swatches to a diagram." d = drawing or Drawing(400, 200) swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 160 swatches.deltax = 60 swatches.dxTextSpace = 10 swatches.columnMaximum = 4 items = [(colors.red, 'before'), (colors.green, 'after')] swatches.colorNamePairs = items d.add(swatches, 'legend') return d
def autoLegender(chart, title='', width=448, height=230, order='off', categories=[], use_colors=[]): d = Drawing(width, height) d.add(chart) lab = Label() lab.x = width / 2 #x和y是title文字的位置坐标 lab.y = 21 / 23 * height lab.fontName = 'song' #增加对中文字体的支持 lab.fontSize = 20 lab.setText(title) d.add(lab) #颜色图例说明等 if categories != [] and use_colors != []: leg = Legend() leg.x = 500 # 说明的x轴坐标 leg.y = 0 # 说明的y轴坐标 leg.boxAnchor = 'se' # leg.strokeWidth = 4 leg.strokeColor = None leg.subCols[1].align = 'right' leg.columnMaximum = 10 # 图例说明一列最多显示的个数 leg.fontName = 'song' leg.alignment = 'right' leg.colorNamePairs = list(zip(use_colors, tuple(categories))) d.add(leg) if order == 'on': d.background = Rect(0, 0, width, height, strokeWidth=1, strokeColor="#868686", fillColor=None) #边框颜色 return d
def add_legend(draw_obj, chart, data): #chart=Pie(); legend = Legend() legend.alignment = 'left' legend.x = 10 legend.y = 70 draw_obj = chart legend.colorNamePairs = Auto(draw_obj=chart)
def add_legend(draw_obj, chart, pos_x, pos_y): """ 函数功能:voltGroupDisplayByBar函数的子函数 :param draw_obj: :param chart: :return: """ legend = Legend() legend.alignment = 'right' legend.fontName = 'song' legend.columnMaximum = 2 legend.x = pos_x legend.y = pos_y legend.colorNamePairs = Auto(obj=chart) draw_obj.add(legend)
def sample2c(): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'right' legend.x = 20 legend.y = 90 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d
def draw_bar(bar_data=[], ax=[], items=[], limit_step=(100, 10), draw_weight=500, draw_height=250): drawing = Drawing(draw_weight, draw_height) bc = VerticalBarChart() bc.x = 35 bc.y = 100 bc.height = 120 bc.width = 350 bc.data = bar_data bc.strokeColor = Config_Charts.chose_colors[15] bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = limit_step[0] bc.valueAxis.valueStep = limit_step[1] bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 20 bc.categoryAxis.categoryNames = ax bc.bars.strokeColor = Config_Charts.chose_colors[148] for index, item in enumerate(items): bc.bars[index].fillColor = item[0] # 图示 leg = Legend() leg.fontName = Config_Charts.typeface leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 465 leg.y = 220 leg.dxTextSpace = 0 leg.columnMaximum = 10 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing
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() pieChartLegend.x = 100 pieChartLegend.y = 100 pieChartLegend.alignment = "right" pieChartLegend.columnMaximum = 5 pieChartLegend.colorNamePairs = [(PCMYKColor(100,0,90,50,alpha=100), ('BP', '30%')), (PCMYKColor(0,100,100,40,alpha=100), ('Shell Transport & Trading', '21%')), (PCMYKColor(100,60,0,50,alpha=100), ('Liberty International', '21%')), (PCMYKColor(23,51,0,4,alpha=100), ('Persimmon', '14%')), (PCMYKColor(66,13,0,22,alpha=100), ('Royal Bank of Scotland', '14%'))] pieChartLegendCanvas.add(pieChartLegend) renderPDF.draw(pieChartLegendCanvas, c, 100, 100) c.showPage() c.save()
def create_single_grade_pdf(grade,content_area_id): '''--Variables--''' school_level = [] Story=[] Elements=[] contentarea_name = "" buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages=[[]] standard_table=[] content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the Content Area Name query = ((content_area_id == db.contentarea.id)) results = db(query).select(db.contentarea.name) for row in results: contentarea_name = row.name #Create the name for the PDf being returned pdfName = "Grade_"+str(grade)+"_"+contentarea_name+"_SR"+".pdf" #set up the response headers so the browser knows to return a PDF document response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] ='attachment;filename=%s;'%pdfName doc = SimpleDocTemplate(buff,pagesize=letter,rightMargin=72,leftMargin=72,topMargin=72,bottomMargin=18) doc.title=pdfName #Set up some styles styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Indent', rightIndent=3)) styles.add(ParagraphStyle(name = 'Title2', parent = styles['Normal'], fontName = 'DejaVuSansCondensed', fontSize = 18, leading = 22, spaceAfter = 6), alias = 'title2') #Time-Stamp ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Administrator ptext='<font size=12><b>Administrator</b></font>' Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>Grade %s %s Standards Report</b></font>'%(grade, contentarea_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1,40)) #Graph Title ptext = '<font size=15><b>Standards Progress</b></font>' Story.append(Paragraph(ptext, styles["title"])) i = 0 #get all the standards for a specific grade and content area standard_query = standard_query = ((db.classes.grade_level == grade)& (db.classes.id == db.student_classes.class_id)& (db.student.id == db.student_classes.student_id)& (db.student.id == db.student_grade.student_id)& (db.grade.id == db.student_grade.grade_id)& (db.grade.id == db.grade_standard.grade_id)& (db.standard.id == db.grade_standard.standard_id)& (db.classes.id == db.class_grade.class_id)& (db.grade.id == db.class_grade.grade_id)& (db.standard.content_area == db.contentarea.id)& (db.contentarea.id == content_area_id)) standard_list = db(standard_query).select(db.standard.id, db.standard.short_name, db.standard.reference_number,db.student_grade.student_score, db.grade.score, db.contentarea.name) standard_ref_list=[] #Setup the Dictionary of standard averages standard_dict = {} for row in standard_list: if row.standard.id in standard_dict.keys(): if((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)): max_score = standard_dict[row.standard.id][0] + row.grade.score student_score = standard_dict[row.standard.id][1] + row.student_grade.student_score standard_dict[row.standard.id] = [max_score, student_score, row.standard.reference_number, row.standard.short_name] else: standard_dict[row.standard.id] = [row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name] standard_table = [] standard_averages=[[]] #set up the 2D list of Standard Averages for standard in sorted(standard_dict.keys()): standard_ref_list.append(standard_dict[standard][2]) standard_table.append([]) current_avg = (standard_dict[standard][1]/standard_dict[standard][0])*100 if minimum > current_avg: minimum = current_avg standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%") standard_averages[0].append(int(round((standard_dict[standard][1]/standard_dict[standard][0])*100))) i+=1 sorted(standard_table,key=lambda l:l[0]) '''---Graph---''' drawing = Drawing(600, 200) data = standard_averages bc = VerticalBarChart() #location in the document (x,y) bc.x = 10 bc.y = 30 #width and height of the graph bc.height = 225 bc.width = 400 bc.data = data bc.categoryAxis.drawGridLast=True bc.categoryAxis.gridStart=0 bc.categoryAxis.gridStrokeLineCap = 2 bc.categoryAxis.gridEnd=3 #bc.barLabels = #Update colors of the bars in the graph bc.bars.symbol = ShadedRect() bc.bars.symbol.fillColorStart = colors.lightblue bc.bars.symbol.fillColorEnd = colors.lightblue bc.bars.symbol.strokeWidth = 0 #this draws a line at the top of the graph to close it. bc.strokeColor = colors.black #Y-axis min, max, and steps. if minimum != 100: bc.valueAxis.valueMin = minimum -10 else: bc.valueAxis.valueMin = 50 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 5 #where to anchor the origin of the graph bc.categoryAxis.labels.boxAnchor = 'ne' #Locations of labels for the X-axis bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -2 bc.barLabels.nudge = -10 bc.barLabelFormat = '%0.2f%%' bc.barLabels.dx = 0 bc.barLabels.dy = 0 #The angle of the lables for the X-axis bc.categoryAxis.labels.angle = 30 #List of the categories to place on the X-axis bc.categoryAxis.categoryNames = standard_ref_list drawing.add(bc) '''------''' '''--Graph Legend--''' #Graph Legend legend = Legend() legend.alignment = 'right' legend.x = 420 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 legend.colorNamePairs = [(colors.lightblue, 'grade average')] drawing.add(legend, 'legend') drawing_title = "Bar Graph" Story.append(drawing) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
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 __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)
xlbl.setOrigin(310, 72) ylbl = Label() ylbl.setText("Percentage\n (%)") ylbl.setOrigin(28, 260) lp.lines[0].strokeColor = colors.darkgreen lp.lineLabels[0].strokeColor = colors.darkgreen lp.lines[1].strokeColor = colors.tomato lp.lineLabels[1].strokeColor = colors.tomato lp.lines[2].strokeColor = colors.aquamarine lp.lineLabels[2].strokeColor = colors.aquamarine lp.lines[3].strokeColor = colors.purple lp.lineLabels[3].strokeColor = colors.purple lgnd = Legend() lgnd.x = 70 lgnd.y = 63 lgnd.autoXPadding = 45 lgnd.colorNamePairs = [ (lp.lines[0].strokeColor, 'Positive'), (lp.lines[1].strokeColor, 'Negative'), (lp.lines[2].strokeColor, 'Norm. Pos.'), (lp.lines[3].strokeColor, 'Norm. Neg.') ] lgnd.demo() d.add(lp) d.add(lgnd) d.add(xlbl) d.add(ylbl) d.save(fnRoot='testLinePlot1', formats=['png', 'pdf'])
def __init__(self): Pie.__init__(self) self.x = 0 self.y = 0 self.height = 100 self.width = 100 self.data = [38.4, 20.7, 18.9, 15.4, 6.6] self.labels = None self.direction = 'clockwise' PCMYKColor, black = colors.PCMYKColor, colors.black self.pieAndLegend_colors = [PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV'), PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV'), PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV',density=75), PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV',density=75), PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV',density=50), PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV',density=50)] #Allows us up to six 'wedges' to be coloured self.slices[0].fillColor=self.pieAndLegend_colors[0] self.slices[1].fillColor=self.pieAndLegend_colors[1] self.slices[2].fillColor=self.pieAndLegend_colors[2] self.slices[3].fillColor=self.pieAndLegend_colors[3] self.slices[4].fillColor=self.pieAndLegend_colors[4] self.slices[5].fillColor=self.pieAndLegend_colors[5] self.slices.strokeWidth = 0.75 self.slices.strokeColor = black legendOffset = 17 self.legendNumberOffset = 51 self.legendNumberFormat = '%.1f%%' self.legend_data = self.data #set up the legends from reportlab.graphics.charts.legends import Legend self.legend1 = Legend() self.legend1.x = self.width+legendOffset self.legend1.y = self.height self.legend1.deltax = 5.67 self.legend1.deltay = 14.17 self.legend1.dxTextSpace = 11.39 self.legend1.dx = 5.67 self.legend1.dy = 5.67 self.legend1.columnMaximum = 7 self.legend1.alignment = 'right' self.legend_names = ['AAA:','AA:','A:','BBB:','NR:'] for f in range(0,len(self.data)): self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], self.legend_names[f])) self.legend1.fontName = "Helvetica-Bold" self.legend1.fontSize = 6 self.legend1.strokeColor = black self.legend1.strokeWidth = 0.5 self._legend2 = Legend() self._legend2.dxTextSpace = 0 self._legend2.dx = 0 self._legend2.alignment = 'right' self._legend2.fontName = "Helvetica-Oblique" self._legend2.fontSize = 6 self._legend2.strokeColor = self.legend1.strokeColor self.leftPadding = 5 self.rightPadding = 5 self.topPadding = 5 self.bottomPadding = 5 self.drawLegend = 1
def autoLegender(i,chart,styleObj,sym='symbol'): if sym: setattr(styleObj[0],sym, makeMarker('Diamond',size=6)) setattr(styleObj[1],sym,makeMarker('Square')) width = 300 height = 150 legend = Legend() legend.x = width-5 legend.y = 5 legend.dx = 20 legend.dy = 5 legend.deltay = 0 legend.boxAnchor = 'se' if i=='col auto': legend.colorNamePairs[0]=(Auto(chart=chart),'auto chart=self.chart') legend.colorNamePairs[1]=(Auto(obj=chart,index=1),'auto chart=self.chart index=1') elif i=='full auto': legend.colorNamePairs=Auto(chart=chart) elif i=='swatch set': legend.swatchMarker=makeMarker('Circle') legend.swatchMarker.size = 10 elif i=='swatch auto': legend.swatchMarker=Auto(chart=chart) d = Drawing(width,height) d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor=colors.red,fillColor=None) m = makeMarker('Cross') m.x = width-5 m.y = 5 m.fillColor = colors.red m.strokeColor = colors.yellow d.add(chart) d.add(legend) d.add(m) return d
def setLegend(self): legend = Legend() legend.colorNamePairs = [] legend.fontName = 'Helvetica-Bold' legend.fontSize = 12 legend.x = 100 legend.y = 110 legend.dxTextSpace = 5 legend.dy = 20 legend.dx = 20 legend.deltay = 5 legend.deltax = 7 legend.columnMaximum = 1 legend.alignment ='right' self.add(legend, name='Legend')
def setLegend(self): legend = Legend() legend.colorNamePairs = [] legend.fontName = 'Helvetica-Bold' legend.fontSize = 12 legend.x = 100 legend.y = 110 legend.dxTextSpace = 5 legend.dy = 20 legend.dx = 20 legend.deltay = 5 legend.deltax = 7 legend.columnMaximum = 1 legend.alignment ='right' legend.x = 60 legend.y = 50 legend.columnMaximum = 2 legend.colorNamePairs = [] legend.colorNamePairs.append((colors.green, self._data_dict['max_score_legend'])) legend.colorNamePairs.append((colors.red, self._data_dict['score_legend'])) self.add(legend, name='Legend')
def create_single_class_pdf( teacher_name, class_id, class_name, class_average, total_students, total_grades, standards_list, grade_standard_dict, grade_student_dict, standard_total_dict, ): pdfName = class_name + "_CLR" + ".pdf" response.headers["Content-Type"] = "application/pdf" response.headers["Content-Disposition"] = "attachment;filename=%s;" % pdfName styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] buff = StringIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) doc.title = pdfName Story = [] Elements = [] formatted_time = time.ctime() styles = getSampleStyleSheet() styles.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name="Indent", rightIndent=3)) styles.add( ParagraphStyle( name="Title2", parent=styles["Normal"], fontName="DejaVuSansCondensed", fontSize=18, leading=22, # alignment = TA_LEFT, spaceAfter=6, ), alias="title2", ) ptext = "<font size=12>%s</font>" % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Teacher Name ptext = "<font size=12><b>%s %s</b></font>" % (teacher_name.first_name, teacher_name.last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Class Name ptext = "<font size=12>%s: </font>" % (class_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) # Class Average ptext = "<font size=12>Class Average:%s%%</font>" % (class_average) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Total Students ptext = "<font size=12>Total Students:%s</font>" % (total_students) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Total Assignments ptext = "<font size=12>Total Assignments:%s</font>" % (total_grades) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Story.append(Spacer(1, 40)) ptext = "<font size=15><b>Standards Progress</b></font>" Story.append(Paragraph(ptext, styles["title"])) test_values = [[10, 20, 50, 90, 80]] standard_table = [] i = 0 minimum = 100 standard_averages = [[]] # Go through the standard_total_dict keys and add all the necessary values to the standard_averages 2d list. for standard in sorted(standard_total_dict.keys()): standard_table.append([]) current_avg = (standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100 if minimum > current_avg: minimum = current_avg standard_table[i].append( standard_total_dict[standard][3] + ": " + format((standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100, ".2f") + "%" ) standard_averages[0].append( int(round((standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100)) ) # add assignments to correct buckets for grade in grade_standard_dict.keys(): for standardId in grade_standard_dict[grade][1]: if standardId == standard: standard_table[i].append( grade_standard_dict[grade][0] + ":" + format((grade_student_dict[grade][1] / grade_student_dict[grade][0]) * 100, ".2f") + "%" ) i += 1 sorted(standard_table, key=lambda l: l[0]) # graph drawing = Drawing(600, 200) data = standard_averages bc = VerticalBarChart() # location in the document (x,y) bc.x = 10 bc.y = 30 # width and height of the graph bc.height = 225 bc.width = 400 bc.data = data bc.categoryAxis.drawGridLast = True bc.categoryAxis.gridStart = 0 bc.categoryAxis.gridStrokeLineCap = 2 bc.categoryAxis.gridEnd = 3 bc.barLabels = [10, 20, 30, 40, 50] # Update colors of the bars in the graph bc.bars.symbol = ShadedRect() bc.bars.symbol.fillColorStart = colors.lightblue bc.bars.symbol.fillColorEnd = colors.lightblue bc.bars.symbol.strokeWidth = 0 # this draws a line at the top of the graph to close it. bc.strokeColor = colors.black # Y-axis min, max, and steps. if minimum != 100: bc.valueAxis.valueMin = minimum - 10 else: bc.valueAxis.valueMin = 50 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 5 # where to anchor the origin of the graph bc.categoryAxis.labels.boxAnchor = "ne" # Locations of labels for the X-axis bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -2 # The angle of the lables for the X-axis bc.categoryAxis.labels.angle = 30 # List of the categories to place on the X-axis bc.categoryAxis.categoryNames = standards_list drawing.add(bc) # Graph Legend legend = Legend() legend.alignment = "right" legend.x = 420 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 legend.colorNamePairs = [(colors.lightblue, "grade average")] drawing.add(legend, "legend") drawing_title = "Bar Graph" Story.append(drawing) t = Table(standard_table) t.setStyle( t.setStyle( TableStyle( [ ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("FONTSIZE", (0, 0), (-1, -1), 7), ("BACKGROUND", (0, 0), (0, -1), colors.lightgrey), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ] ) ) ) Story.append(t) doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def make_graphs(self,canvas=None,left_margin=None):#text=None): from reportlab.graphics import renderPDF from reportlab.lib.pagesizes import letter from reportlab.graphics.shapes import Drawing,String from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors from reportlab.lib.units import inch #help(colors) self.framework = {4:dict(status=SpotClass.SPINDLE,color=colors.black), 5:dict(status=SpotClass.OVERLAP,color=colors.limegreen), 6:dict(status=SpotClass.OUTLIER,color=colors.greenyellow), 7:dict(status=SpotClass.ICE,color=colors.skyblue), } # set size and position width,height = letter #letter_landscape = (width,height) plot_dim = 3.0*inch # construct scatter plot plot_dxdy_pos = (left_margin*inch,height - plot_dim - 0.5*inch) plot_dxdy = LinePlot() plot_dxdy.data = self.plot_dxdy_data std_colors = {0:colors.darkred, 1:colors.red, 2:colors.salmon} for key in std_colors.keys(): plot_dxdy.lines[key].strokeColor = None plot_dxdy.lines[key].symbol = makeMarker('Circle') plot_dxdy.lines[key].symbol.strokeColor = None plot_dxdy.lines[key].symbol.fillColor = std_colors[key] plot_dxdy.lines[key].symbol.size = 1.2 for key in self.framework.keys(): plot_dxdy.lines[key].strokeColor = None plot_dxdy.lines[key].symbol = makeMarker('Circle') plot_dxdy.lines[key].symbol.strokeColor = None plot_dxdy.lines[key].symbol.fillColor = self.framework[key]["color"] plot_dxdy.lines[key].symbol.size = 1.2 plot_dxdy.lines[3].strokeColor = None plot_dxdy.lines[3].symbol = makeMarker('Circle') plot_dxdy.lines[3].symbol.strokeColor = colors.blue plot_dxdy.lines[3].symbol.fillColor = None plot_dxdy.lines[3].symbol.strokeWidth = 0.6 plot_dxdy.lines[3].symbol.size = plot_dim*(self.sqrtr2) #print plot_dxdy.lines[3].symbol.getProperties() plot_dxdy.width = plot_dim plot_dxdy.height = plot_dim plot_dxdy.xValueAxis.valueMax = 1.0 plot_dxdy.xValueAxis.valueMin = -1.0 plot_dxdy.xValueAxis.joinAxis = plot_dxdy.yValueAxis plot_dxdy.xValueAxis.joinAxisMode = 'value' plot_dxdy.xValueAxis.joinAxisPos = -1.0 plot_dxdy.yValueAxis.valueMax = 1.0 plot_dxdy.yValueAxis.valueMin = -1.0 d_dxdy = Drawing(plot_dim,plot_dim) d_dxdy.add(plot_dxdy) # construct cdf plot plot_cdf_pos = (left_margin*inch, height - 2.0*(plot_dim + 0.5*inch)) plot_cdf = LinePlot() plot_cdf.data = self.plot_cdf_data plot_cdf.lines[0].strokeColor = colors.blue for key in std_colors.keys(): plot_cdf.lines[key+1].strokeColor = None plot_cdf.lines[key+1].symbol = makeMarker('Circle') plot_cdf.lines[key+1].symbol.strokeColor = None plot_cdf.lines[key+1].symbol.fillColor = std_colors[key] plot_cdf.lines[key+1].symbol.size = 1.2 if (len(self.plot_cdf_data) == 5): plot_cdf.lines[4].strokeColor = colors.green plot_cdf.width = plot_dim plot_cdf.height = plot_dim plot_cdf.xValueAxis.valueMax = 1.0 plot_cdf.xValueAxis.valueMin = 0.0 plot_cdf.yValueAxis.valueMax = 1.0 plot_cdf.yValueAxis.valueMin = 0.0 d_cdf = Drawing(plot_dim,plot_dim) d_cdf.add(plot_cdf) # construct pdf plot plot_pdf_pos = (left_margin*inch, height - 3.0*(plot_dim + 0.5*inch)) plot_pdf = LinePlot() plot_pdf.data = self.plot_pdf_data plot_pdf.lines[1].strokeColor = colors.blue plot_pdf.lines[0].strokeColor = None plot_pdf.lines[0].symbol = makeMarker('Circle') plot_pdf.lines[0].symbol.strokeColor = colors.red plot_pdf.lines[0].symbol.size = 1 plot_pdf.width = plot_dim plot_pdf.height = plot_dim plot_pdf.xValueAxis.valueMax = 1.0 plot_pdf.xValueAxis.valueMin = 0.0 d_pdf = Drawing(2*plot_dim,plot_dim) d_pdf.add(plot_pdf) # add legend legend = Legend() legend.alignment = 'right' legend.colorNamePairs = [(std_colors[0],'Inliers (%d'%int(self.fraction*100.0) + '% used for fit)'), (std_colors[1],'Other inliers'), (std_colors[2],'Outliers, reject next round'),] for key in self.framework.keys(): legend.colorNamePairs.append( (self.framework[key]["color"], "%s"%self.framework[key]["status"] ) ) legend.x = plot_dim - 1.0*inch legend.y = plot_dim legend.columnMaximum = 8 d_pdf.add(legend) # add titles title_pos = (plot_dim/2.0,plot_dim + 0.25*inch) title_dxdy = String(title_pos[0],title_pos[1],'dx vs. dy (all)') title_dxdy.fontSize = 15 title_dxdy.textAnchor = 'middle' d_dxdy.add(title_dxdy) title_cdf = String(title_pos[0],title_pos[1],'cdf (good)') title_cdf.fontSize = 15 title_cdf.textAnchor = 'middle' d_cdf.add(title_cdf) title_pdf = String(title_pos[0],title_pos[1],'pdf (good)') title_pdf.fontSize = 15 title_pdf.textAnchor = 'middle' d_pdf.add(title_pdf) # draw everything renderPDF.draw(d_dxdy,canvas,plot_dxdy_pos[0],plot_dxdy_pos[1]) renderPDF.draw(d_cdf,canvas,plot_cdf_pos[0],plot_cdf_pos[1]) renderPDF.draw(d_pdf,canvas,plot_pdf_pos[0],plot_pdf_pos[1])
# Set bar colors for i in range(len(colors)): chart.bars[i].fillColor = colors[i] # Add data to chart chart.data = prices chart.categoryAxis.categoryNames = categories # Add labels to chart chart.barLabelFormat = '$%.2f' # Text to display on label - 2 decimal float chart.barLabels.nudge = 8 # Nudge labels upwards by 8px # ------- Create legend ------- legend = Legend() # Create the legend legend.boxAnchor = 'sw' # Set anchor to bottom-left legend.x = 50 # Shift legend right to bring in line with chart legend.y = 50 # Shift legend up by 50px legend.alignment = 'right' # Put labels to the right of color icons # Set legend colors legend.colorNamePairs = [(colors[i], '{} '.format(labels[i])) for i in range(len(colors))] # Add chart and legend to drawing d.add(chart) d.add(legend) # Export as test_img.png d.save(fnRoot='test_img', formats=['png'])
def create_single_grade_pdf(student_id, class_id, assignment_count, grade_standard_dict, grade_student_dict, assignment_line_all, assignment_names, assignment_dict): '''--Variables--''' Story=[] Elements=[] buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages=[[]] standard_table=[] #content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the student Name #Create the name for the PDf being returned pdfName = get_student_name(student_id).first_name+"_"+get_student_name(student_id).last_name+"_SR"+".pdf" #set up the response headers so the browser knows to return a PDF document response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] ='attachment;filename=%s;'%pdfName doc = SimpleDocTemplate(buff,pagesize=letter,rightMargin=72,leftMargin=72,topMargin=72,bottomMargin=18) doc.title=pdfName #Set up some styles styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Indent', rightIndent=3)) styles.add(ParagraphStyle(name = 'Title2', parent = styles['Normal'], fontName = 'DejaVuSansCondensed', fontSize = 18, leading = 22, #alignment = TA_LEFT, spaceAfter = 6), alias = 'title2') #Time-Stamp ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Administrator ptext='<font size=12><b>%s %s</b></font>'%(get_student_name(student_id).first_name, get_student_name(student_id).last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>%s Student Report</b></font>'%(get_class_name(class_id).name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) #Total Assignments ptext = '<font size=12>Total Assignments: %s</font>'%(assignment_count) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1,20)) #Graph Title ptext = '<font size=15><b>Current Performance by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,50)) #get all the standards for a specific grade and content area standard_query = ((db.classes.id == class_id)& (student_id == db.student.id)& (db.classes.id == db.student_classes.class_id)& (db.student.id == db.student_classes.student_id)& (db.student.id == db.student_grade.student_id)& (db.grade.id == db.student_grade.grade_id)& (db.grade.id == db.grade_standard.grade_id)& (db.standard.id == db.grade_standard.standard_id)& (db.classes.id == db.class_grade.class_id)& (db.grade.id == db.class_grade.grade_id)& (db.standard.content_area == db.contentarea.id)) standard_list = db(standard_query).select(db.standard.id, db.standard.short_name, db.standard.reference_number,db.student_grade.student_score, db.grade.score, db.contentarea.name) standard_ref_list=[] #Setup the Dictionary of standard averages standard_dict = {} standard_table = [] standard_averages=[[]] for row in standard_list: if row.standard.id in standard_dict.keys(): if((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)): max_score = standard_dict[row.standard.id][0] + row.grade.score student_score = standard_dict[row.standard.id][1] + row.student_grade.student_score standard_dict[row.standard.id] = [max_score, student_score, row.standard.reference_number, row.standard.short_name] else: standard_dict[row.standard.id] = [row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name] i = 0 #set up the 2D list of Standard Averages for standard in sorted(standard_dict.keys()): standard_ref_list.append(standard_dict[standard][2]) standard_table.append([]) current_avg = (standard_dict[standard][1]/standard_dict[standard][0])*100 if minimum > current_avg: minimum = current_avg #int/round was here standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%") #int/round was here standard_averages[0].append((standard_dict[standard][1]/standard_dict[standard][0])*100) for grade in grade_standard_dict.keys(): for standardId in grade_standard_dict[grade][1]: if(standardId == standard): standard_table[i].append(grade_standard_dict[grade][0]+":"+format((grade_student_dict[grade][1]/grade_student_dict[grade][0])*100, '.2f')+"%") i+=1 sorted(standard_table,key=lambda l:l[0]) '''---Graph---''' drawing = Drawing(600, 200) data = standard_averages bc = VerticalBarChart() #location in the document (x,y) bc.x = 10 bc.y = 30 #width and height of the graph bc.height = 225 bc.width = 400 bc.data = data bc.categoryAxis.drawGridLast=True bc.categoryAxis.gridStart=0 bc.categoryAxis.gridStrokeLineCap = 2 bc.categoryAxis.gridEnd=3 #bc.barLabels = #Update colors of the bars in the graph bc.bars.symbol = ShadedRect() bc.bars.symbol.fillColorStart = colors.lightblue bc.bars.symbol.fillColorEnd = colors.lightblue bc.bars.symbol.strokeWidth = 0 #this draws a line at the top of the graph to close it. bc.strokeColor = colors.black #Y-axis min, max, and steps. if minimum != 100: bc.valueAxis.valueMin = minimum -10 else: bc.valueAxis.valueMin = 50 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 5 #where to anchor the origin of the graph bc.categoryAxis.labels.boxAnchor = 'ne' #Locations of labels for the X-axis bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -2 bc.barLabels.nudge = -10 bc.barLabelFormat = '%.2f%%' bc.barLabels.dx = 0 bc.barLabels.dy = 0 #The angle of the lables for the X-axis bc.categoryAxis.labels.angle = 30 #List of the categories to place on the X-axis bc.categoryAxis.categoryNames = standard_ref_list drawing.add(bc) '''------''' '''--Graph Legend--''' #Graph Legend legend = Legend() legend.alignment = 'right' legend.x = 420 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 legend.colorNamePairs = [(colors.lightblue, 'grade average')] drawing.add(legend, 'legend') drawing_title = "Bar Graph" Story.append(drawing) Story.append(Spacer(1,15)) #LineGraph Title ptext = '<font size=15><b>Class Performance by Assignment</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,30)) ''' Line Plot Graph ------ ''' assignment_data_all =[[],[]] for key in assignment_dict.keys(): assignment_data_all[0].append(assignment_dict[key][2]) assignment_data_all[1].append(assignment_dict[key][1]) drawing2 = Drawing(600, 200) data2 = assignment_data_all #lp = LinePlot() #data[0] = preprocessData(data[0]) lp = HorizontalLineChart() lp.x = -20 lp.y = 0 lp.height = 225 lp.width = 500 lp.data = data2 lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.lines[0].strokeColor = colors.grey lp.lines[1].strokeColor = colors.lightblue lp.strokeColor = colors.black lp.categoryAxis.labels.fontSize = 7 lp.categoryAxis.categoryNames = assignment_names lp.categoryAxis.labels.boxAnchor = 'ne' lp.categoryAxis.labels.angle = 30 lp.categoryAxis.drawGridLast=True #lp.categoryAxis.gridStart=0 lp.categoryAxis.gridStrokeLineCap = 2 #lp.categoryAxis.gridEnd=3 #lp.categoryAxis.visibleGrid = 1 lp.valueAxis.visibleGrid = 1 lp.valueAxis.visible = 1 lp.valueAxis.drawGridLast=False #lp.valueAxis.gridStart = 0 #lp.valueAxis.gridEnd = 100 lp.valueAxis.gridStrokeColor = colors.black lp.valueAxis.valueMin = 0 lp.valueAxis.valueMax = 105 lp.valueAxis.valueStep = 10 lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.fillColor = colors.white drawing2.add(lp) legend = Legend() legend.alignment = 'right' legend.x = 482 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 2 legend.colorNamePairs = [(colors.lightblue, 'Student'),(colors.grey, 'Class')] drawing2.add(legend, 'legend') Story.append(drawing2) Story.append(Spacer(1,30)) ptext = '<font size=15><b>Assignments by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,10)) t=Table(standard_table) t.setStyle(t.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 7), ('BACKGROUND',(0,0),(0,-1),colors.lightgrey), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),]))) Story.append(t) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
class LegendedPie(Pie): """Pie with a two part legend (one editable with swatches, one hidden without swatches).""" _attrMap = AttrMap(BASE=Pie, drawLegend = AttrMapValue(isBoolean, desc="If true then create and draw legend"), legend1 = AttrMapValue(None, desc="Handle to legend for pie"), legendNumberFormat = AttrMapValue(None, desc="Formatting routine for number on right hand side of legend."), legendNumberOffset = AttrMapValue(isNumber, desc="Horizontal space between legend and numbers on r/hand side"), pieAndLegend_colors = AttrMapValue(isListOfColors, desc="Colours used for both swatches and pie"), legend_names = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="Names used in legend (or None)"), legend_data = AttrMapValue(isNoneOrListOfNoneOrNumbers, desc="Numbers used on r/hand side of legend (or None)"), leftPadding = AttrMapValue(isNumber, desc='Padding on left of drawing'), rightPadding = AttrMapValue(isNumber, desc='Padding on right of drawing'), topPadding = AttrMapValue(isNumber, desc='Padding at top of drawing'), bottomPadding = AttrMapValue(isNumber, desc='Padding at bottom of drawing'), ) def __init__(self): Pie.__init__(self) self.x = 0 self.y = 0 self.height = 100 self.width = 100 self.data = [38.4, 20.7, 18.9, 15.4, 6.6] self.labels = None self.direction = 'clockwise' PCMYKColor, black = colors.PCMYKColor, colors.black self.pieAndLegend_colors = [PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV'), PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV'), PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV',density=75), PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV',density=75), PCMYKColor(11,11,72,0,spotName='PANTONE 458 CV',density=50), PCMYKColor(100,65,0,30,spotName='PANTONE 288 CV',density=50)] #Allows us up to six 'wedges' to be coloured self.slices[0].fillColor=self.pieAndLegend_colors[0] self.slices[1].fillColor=self.pieAndLegend_colors[1] self.slices[2].fillColor=self.pieAndLegend_colors[2] self.slices[3].fillColor=self.pieAndLegend_colors[3] self.slices[4].fillColor=self.pieAndLegend_colors[4] self.slices[5].fillColor=self.pieAndLegend_colors[5] self.slices.strokeWidth = 0.75 self.slices.strokeColor = black legendOffset = 17 self.legendNumberOffset = 51 self.legendNumberFormat = '%.1f%%' self.legend_data = self.data #set up the legends from reportlab.graphics.charts.legends import Legend self.legend1 = Legend() self.legend1.x = self.width+legendOffset self.legend1.y = self.height self.legend1.deltax = 5.67 self.legend1.deltay = 14.17 self.legend1.dxTextSpace = 11.39 self.legend1.dx = 5.67 self.legend1.dy = 5.67 self.legend1.columnMaximum = 7 self.legend1.alignment = 'right' self.legend_names = ['AAA:','AA:','A:','BBB:','NR:'] for f in range(0,len(self.data)): self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], self.legend_names[f])) self.legend1.fontName = "Helvetica-Bold" self.legend1.fontSize = 6 self.legend1.strokeColor = black self.legend1.strokeWidth = 0.5 self._legend2 = Legend() self._legend2.dxTextSpace = 0 self._legend2.dx = 0 self._legend2.alignment = 'right' self._legend2.fontName = "Helvetica-Oblique" self._legend2.fontSize = 6 self._legend2.strokeColor = self.legend1.strokeColor self.leftPadding = 5 self.rightPadding = 5 self.topPadding = 5 self.bottomPadding = 5 self.drawLegend = 1 def draw(self): if self.drawLegend: self.legend1.colorNamePairs = [] self._legend2.colorNamePairs = [] for f in range(0,len(self.data)): if self.legend_names == None: self.slices[f].fillColor = self.pieAndLegend_colors[f] self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], None)) else: try: self.slices[f].fillColor = self.pieAndLegend_colors[f] self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f], self.legend_names[f])) except IndexError: self.slices[f].fillColor = self.pieAndLegend_colors[f%len(self.pieAndLegend_colors)] self.legend1.colorNamePairs.append((self.pieAndLegend_colors[f%len(self.pieAndLegend_colors)], self.legend_names[f])) if self.legend_data != None: ldf = self.legend_data[f] lNF = self.legendNumberFormat from types import StringType if ldf is None or lNF is None: pass elif type(lNF) is StringType: ldf = lNF % ldf elif callable(lNF): ldf = lNF(ldf) else: p = self.legend_names[f] if self.legend_data != None: ldf = self.legend_data[f] lNF = self.legendNumberFormat if ldf is None or lNF is None: pass elif type(lNF) is StringType: ldf = lNF % ldf elif callable(lNF): ldf = lNF(ldf) else: msg = "Unknown formatter type %s, expected string or function" % self.legendNumberFormat raise Exception, msg self._legend2.colorNamePairs.append((None,ldf)) p = Pie.draw(self) if self.drawLegend: p.add(self.legend1) #hide from user - keeps both sides lined up! self._legend2.x = self.legend1.x+self.legendNumberOffset self._legend2.y = self.legend1.y self._legend2.deltax = self.legend1.deltax self._legend2.deltay = self.legend1.deltay self._legend2.dy = self.legend1.dy self._legend2.columnMaximum = self.legend1.columnMaximum p.add(self._legend2) p.shift(self.leftPadding, self.bottomPadding) return p def _getDrawingDimensions(self): tx = self.rightPadding if self.drawLegend: tx = tx+self.legend1.x+self.legendNumberOffset #self._legend2.x tx = tx + self._legend2._calculateMaxWidth(self._legend2.colorNamePairs) ty = self.bottomPadding+self.height+self.topPadding return (tx,ty) def demo(self, drawing=None): if not drawing: tx,ty = self._getDrawingDimensions() drawing = Drawing(tx, ty) drawing.add(self.draw()) return drawing
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)
lp.xValueAxis.labels.dy = -10 lp.xValueAxis.labels.boxAnchor = 'e' lp.yValueAxis.labelTextFormat = lambda value: '%d MB' % (int(value) / 1000) lp.yValueAxis.labels.fontName = 'Helvetica' lp.yValueAxis.labels.fontSize = 7 lp.yValueAxis.visibleGrid = True lp.yValueAxis.drawGridLast = True lp.yValueAxis.valueMin = 0 if reserved: if reserved[0]: lp.yValueAxis.valueMax = reserved[0] if reserved[1]: lp.yValueAxis.valueStep = reserved[1] for i in range(len(names)): lp.lines[i].strokeColor = self.Color[i] legend = Legend() legend.x = 0 legend.y = h - 30 legend.boxAnchor = 'sw' legend.colorNamePairs = [(self.Color[i], names[i]) for i in range(len(names))] legend.fontName = 'Helvetica' legend.fontSize = 8 legend.dxTextSpace = 5 legend.dy = 5 legend.dx = 5 legend.deltay = 5 legend.alignment ='right' drawing.add(lp) drawing.add(legend)
def run(self): def weight_sort(a, b): return cmp(a.getWeight(), b.getWeight()) drawing = Drawing(600, 300) lc = LinePlot() # Determine axis dimensions and create data set maxval = 0 minval = 0 dimension_one_values = [] dimension_two_values = [] dimension_one_answeroptions_as_objects = [] dimension_two_answeroptions_as_objects = [] counter = 0 for question in self.getQuestions(): weights = [int(weight) for weight in question.getAnswerOptionsWeights()] answeroptions = list(question.getAnswerOptions()) # This is used by the legend. Sort on weight. if counter == 0: dimension_one_answeroptions_as_objects = question.getAnswerOptionsAsObjects() dimension_one_answeroptions_as_objects.sort(weight_sort) else: dimension_two_answeroptions_as_objects = question.getAnswerOptionsAsObjects() dimension_two_answeroptions_as_objects.sort(weight_sort) # Minmax lmin = min(weights) lmax = max(weights) if lmin < minval: minval = lmin if lmax > maxval: maxval = lmax # Data for user, answer in question.answers.items(): value = answer.get('value', None) weight = None if value is not None: # Lookup the integer weight of this answer if value in answeroptions: index = answeroptions.index(value) weight = weights[index] # Always add to the list. ReportLab deals with None. if counter == 0: dimension_one_values.append(weight) else: dimension_two_values.append(weight) counter += 1 # Set minmax absmax = max(abs(minval), abs(maxval)) * 1.1 lc.xValueAxis.valueMin = -absmax lc.xValueAxis.valueMax = absmax lc.yValueAxis.valueMin = -absmax lc.yValueAxis.valueMax = absmax # Zip to create data data = [zip(dimension_one_values, dimension_two_values)] if not len(data[0]): return lc.x = 0 lc.y = 0 # Misc setup lc.height = 300 lc.width = 300 lc.data = data lc.joinedLines = 0 lc.fillColor = None lc.lines[0].strokeColor = colors.red lc.lines[0].symbol = makeMarker('FilledCircle') # Add a grid grid = DoubleGrid() lc.background = grid setupGrid(lc) lc.background = None # Finetune the grid grid.grid0.strokeWidth = 0.2 grid.grid1.strokeWidth = 0.2 # Add to drawing else it overwrites the center Y axis drawing.add(grid) # Add a Y axis to pass through the origin yaxis = YValueAxis() yaxis.setPosition(lc.width/2, 0, lc.height) yaxis.configure([(0,-absmax),(0,absmax)]) yaxis.strokeColor = colors.blue drawing.add(yaxis) # Color X-Axis lc.xValueAxis.strokeColor = colors.green drawing.add(lc) # Legend for Dimension One drawing.add(String(lc.width+20, lc.height-12, 'Dimension One (X-Axis):', fontName='Helvetica', fontSize=12, fillColor=colors.green)) legend = Legend() legend.alignment = 'right' legend.x = lc.width + 20 legend.y = lc.height - 20 legend.fontName = 'Helvetica' legend.fontSize = 12 legend.columnMaximum = 7 items = [] for ob in dimension_one_answeroptions_as_objects: items.append( ( StringWidget(ob.getWeight()), ob() ) ) legend.colorNamePairs = items drawing.add(legend, 'legend1') # Legend for Dimension Two drawing.add(String(lc.width+20, lc.height/2-12, 'Dimension Two (Y-Axis):', fontName='Helvetica', fontSize=12, fillColor=colors.blue)) legend = Legend() legend.alignment = 'right' legend.x = lc.width + 20 legend.y = lc.height/2 - 20 legend.fontName = 'Helvetica' legend.fontSize = 12 legend.columnMaximum = 7 items = [] for ob in dimension_two_answeroptions_as_objects: items.append( ( StringWidget(ob.getWeight()), ob() ) ) legend.colorNamePairs = items drawing.add(legend, 'legend2') # Write out data = drawing.asString('png') request = self.REQUEST response = request.RESPONSE response.setHeader('Content-Type', 'image/png') response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId()) response.setHeader('Content-Length', len(data)) response.setHeader('Cache-Control', 's-maxage=0') return data
def autoLegender(i, chart, styleObj, sym="symbol"): if sym: setattr(styleObj[0], sym, makeMarker("Diamond", size=6)) setattr(styleObj[1], sym, makeMarker("Square")) width = 300 height = 150 legend = Legend() legend.x = width - 5 legend.y = 5 legend.dx = 20 legend.dy = 5 legend.deltay = 0 legend.boxAnchor = "se" if i == "col auto": legend.colorNamePairs[0] = (Auto(chart=chart), "auto chart=self.chart") legend.colorNamePairs[1] = (Auto(obj=chart, index=1), "auto chart=self.chart index=1") elif i == "full auto": legend.colorNamePairs = Auto(chart=chart) elif i == "swatch set": legend.swatchMarker = makeMarker("Circle") legend.swatchMarker.size = 10 elif i == "swatch auto": legend.swatchMarker = Auto(chart=chart) d = Drawing(width, height) d.background = Rect(0, 0, width, height, strokeWidth=1, strokeColor=colors.red, fillColor=None) m = makeMarker("Cross") m.x = width - 5 m.y = 5 m.fillColor = colors.red m.strokeColor = colors.yellow d.add(chart) d.add(legend) d.add(m) return d
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 createCitationHistogram(self): ''' Routine to create a histogram of citations: 1. refereed papers to refereed papers 2. refereed papers to non-refereed papers 3. non-refereed papers to refereed papers 4. non-refereed papers to non-refereed papers (where 'to X' means 'to the papers of type X in the publication set, used to generate the metrics) ''' # The vertical bar chart will get added to the 'drawing' object drawing = Drawing(400, 200) # Now we can start constructing the vertical bar chart lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 # Record the publication years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['citation histogram'].keys()))) # This list will hold the data points for the histogram lc.data = [] # Record the counts for the 4 different types of citations ref_ref = [] ref_non = [] non_ref = [] non_non = [] # The maximum number of citations will be used to scale the y axis max_citations = 0 # Take only the first four values of each value string in the histogram data for year in years: values = map(lambda a: int(a),self.data['citation histogram'][str(year)].split(':')[:4]) all2all = values[0] all2ref = values[2] ref2ref = values[3] ref2all = values[1] all2non = all2all - all2ref ref2non = ref2all - ref2ref non2all = all2all - ref2all non2ref = all2ref - ref2ref non2non = non2all - non2ref ref_ref.append(ref2ref) ref_non.append(ref2non) non_ref.append(non2ref) non_non.append(non2non) max_citations = max(max_citations,ref2ref,ref2non,non2ref,non2non) lc.data.append(ref_ref) lc.data.append(ref_non) lc.data.append(non_ref) lc.data.append(non_non) # If there are no citations, just omit this histogram: if max_citations == 0: return # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lc.categoryAxis.labels.dx = -6 lc.categoryAxis.labels.dy = -6 # and rotate the labels by 90 degrees lc.categoryAxis.labels.angle = 90 # The label names are the publication years lc.categoryAxis.categoryNames = map(lambda a: str(a), years) # Define the colors for the various bars lc.bars[0].fillColor = colors.red lc.bars[1].fillColor = colors.green lc.bars[2].fillColor = colors.blue lc.bars[3].fillColor = colors.orange # Define the value step and maximum for the y axis lc.valueAxis.valueMax = int(math.ceil(float(max_citations)/10.0))*10 lc.valueAxis.valueStep = max(int(math.floor(float(max_citations)/10.0)),1) # Now add the histogram to the 'drawing' object drawing.add(lc) # Add a legend to the histogram so that we now which color means what legend = Legend() legend.alignment = 'right' legend.x = 380 legend.y = 160 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 6 items = [(colors.red, 'refereed to refereed'), (colors.green, 'refereed to non-refereed'),(colors.blue, 'non-refereed to refereed'),(colors.orange, 'non-refereed to non-refereed')] legend.colorNamePairs = items drawing.add(legend, 'legend') # Finally add a title to the histogram drawing.add(String(200,190,"citation histogram", textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
def addAutoLegend(self,chart,offset,num,side='bottom'): from reportlab.lib.validators import Auto width = 300 height = 150 legend = Legend() if side == 'bottom': legend.x = offset[0]-15 legend.dx = 20 legend.dy = 5 legend.y = offset[1]-25 legend.deltax = None legend.autoXPadding = 35 legend.deltay = 5 legend.boxAnchor = 'nw' legend.dxTextSpace = 5 legend.columnMaximum = (num/3) if num%3 >0: legend.columnMaximum += 1 legend.variColumn = True elif side == 'right': legend.x = offset[0]+offset[2]+40 legend.dx = 20 legend.dy = 5 legend.y = offset[1]+offset[3]-15 legend.deltax = None legend.deltay = 5 legend.boxAnchor = 'nw' legend.dxTextSpace = 5 legend.columnMaximum = 9 legend.colorNamePairs=Auto(chart=chart) return legend