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 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
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 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 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 getContents(self): pie = self.pie data = [v for v in pie.data] total = sum(data) ndata = len(data) lv = [' %.2f%%' % v for v in data] labels = self._labels[:] labels += max(len(lv) - len(labels), 0) * [''] labels = [lab + lv[i] for i, lab in enumerate(labels)] fontName = self._fontName legend = self.legend legend.fontName = fontName colors = list(map(toColor, self._colors)) ncolors = len(colors) colors += [ Whiter(colors[i % ncolors], 0.7**(1 + i // ncolors)) for i in range(max(ndata - ncolors, 0)) ] for i in range(ndata): self.pie.slices[i].fillColor = colors[i] for i in range(ndata): legend.colorNamePairs.append((colors[i], labels[i])) if total < 99.9: data.append(100 - total) if total < 99.9: self.pie.slices[ndata].fillColor = None if total < 99.9: legend.colorNamePairs.append( (Auto(obj=self.pie), 'Unknown %.2f%%' % (100 - total))) self.pie.data = data return Drawing.getContents(self)
def sample4pie(): width = 300 height = 150 d = Drawing(width, height) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [1, 50, 100, 100, 100, 100, 100, 100, 100, 50] pc.labels = ['0','a','b','c','d','e','f','g','h','i'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 20 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red d.add(pc) legend = Legend() legend.x = width-5 legend.y = height-5 legend.dx = 20 legend.dy = 5 legend.deltax = 0 legend.boxAnchor = 'nw' legend.colorNamePairs=Auto(chart=pc) d.add(legend) return d
def add_legend(draw_obj, chart, data): legend = Legend() legend.alignment = 'right' legend.x = 10 legend.y = 70 legend.colorNamePairs = Auto(obj=chart) draw_obj.add(legend)
def add_legend1(draw_obj, chart, data, doc): legend = LineLegend() legend.alignment = 'right' legend.x = doc.leftMargin legend.y = doc.bottomMargin - 30 legend.colorNamePairs = Auto(obj=chart) draw_obj.add(legend)
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 __init__(self, raw_data, width=600, height=300, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.add(VerticalBarChart3D(), name='bc') self.bc.x = 20 self.bc.y = 20 self.bc.width = width - 200 self.bc.height = height - 40 self.bc.barWidth = 5 self.bc.data = [tuple(raw_data[1]), tuple(raw_data[2])] self.bc.valueAxis.valueMax = max( [max(self.bc.data[0]), max(self.bc.data[1])]) + 1 self.bc.categoryAxis.categoryNames = raw_data[0] self.add(Legend(), name='legend') self.legend.x = self.bc.width + 40 self.legend.y = height // 2 self.legend.colorNamePairs = [ (Auto(chart=self.bc), 'Arbeitsunfälle gesamt'.encode('utf-8')), (Auto(chart=self.bc), 'davon Wegeunfälle'.encode('utf-8')), ] self.legend.fontSize = 14 self.legend.alignment = 'right'
def sample1barline( data=[(100, 110, 120, 130), (70, 25, 85, 30), (63, 75, 51, 92), (51, 21, 66, 71), (10, 11, 90, 30)], seriesOrder=[[0, 3, 1], [4], [2]], lines=[3, 4], cAStyle='mixed', ): d = Drawing(400, 250) chart = VerticalBarChart() d.add(chart, name='chart') leg = Legend() d.add(leg, name='leg') chart.bars.strokeColor = None chart.bars[2].fillColor = colors.blue chart.bars[3].fillColor = colors.orange chart.bars[4].fillColor = colors.black #yellow chart.bars[4].strokeWidth = 3 chart.bars[4].symbol = makeMarker('FilledDiamond', size=10, fillColor=colors.red) chart.barSpacing = 1 chart.categoryAxis.style = cAStyle chart.data = data chart.x = 20 chart.y = 70 chart.height = d.height - chart.y - 10 chart.valueAxis.forceZero = True chart.width = d.width - chart.x - 10 for i in lines: chart.bars[i].isLine = 1 for i in lines: chart.bars[i].strokeWidth = 2 leg.colorNamePairs = Auto(chart=chart) leg.x = d.width / 2 leg.y = 5 leg.boxAnchor = 's' leg.columnMaximum = 1 leg.alignment = 'right' return d
def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs, 'chart', getattr(colorNamePairs, 'obj', None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self, 'swatchMarker', None) if isAuto(swatchMarker): chart = getattr(swatchMarker, 'chart', getattr(swatchMarker, 'obj', None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor subCols = self.subCols leading = fontSize * 1.2 yGap = self.yGap if not deltay: deltay = max(dy, leading) + self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxBoundaries(colorNamePairs) nCols = int((n + columnMaximum - 1) / (columnMaximum * 1.0)) xW = dx + dxTextSpace + self.autoXPadding variColumn = self.variColumn if variColumn: width = reduce(operator.add, [m[-1] for m in maxWidth], 0) + xW * nCols else: deltax = max(maxWidth[-1] + xW, deltax) width = maxWidth[-1] + nCols * deltax maxWidth = nCols * [maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne', 'n', 'nw', 'autoy'): height = self._calcHeight() if ba in ('e', 'c', 'w'): thisy += height / 2. else: thisy += height if ba not in ('nw', 'w', 'sw', 'autox'): if ba in ('n', 'c', 's'): thisx -= width / 2 else: thisx -= width upperlefty = thisy g = Group() ascent = getFont(fontName).face.ascent / 1000. if ascent == 0: ascent = 0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self, 'callout', None) scallout = getattr(self, 'swatchCallout', None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in xrange(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker, 'chart', getattr(swatchMarker, 'obj', None)).getSeriesName( i, 'series %d' % i) T = _getLines(name) S = [] aS = S.append j = int(i / (columnMaximum * 1.0)) jOffs = maxWidth[j] # thisy+dy/2 = y+leading/2 y = y0 = thisy + (dy - ascent) * 0.5 if callout: callout(self, g, thisx, y, (col, name)) if alignment == "left": x = thisx xn = thisx + jOffs[-1] + dxTextSpace elif alignment == "right": x = thisx + dx + dxTextSpace xn = thisx else: raise ValueError, "bad alignment" if not isSeqType(name): T = [T] yd = y for k, lines in enumerate(T): y = y0 kk = k * 2 x1 = x + jOffs[kk] x2 = x + jOffs[kk + 1] sc = subCols[k, i] anchor = sc.align fN = getattr(sc, 'fontName', fontName) fS = getattr(sc, 'fontSize', fontSize) fC = getattr(sc, 'fillColor', fillColor) fL = getattr(sc, 'leading', 1.2 * fontSize) if fN == fontName: fA = (ascent * fS) / fontSize else: fA = getFont(fontName).face.ascent / 1000. if fA == 0: fA = 0.718 fA *= fS if anchor == 'left': anchor = 'start' xoffs = x1 elif anchor == 'right': anchor = 'end' xoffs = x2 elif anchor == 'numeric': xoffs = x2 else: anchor = 'middle' xoffs = 0.5 * (x1 + x2) for t in lines: aS( String(xoffs, y, t, fontName=fN, fontSize=fS, fillColor=fC, textAnchor=anchor)) y -= fL yd = min(yd, y) y += fL for iy, a in ((y - max(fL - fA, 0), 'underlines'), (y + fA, 'overlines')): il = getattr(sc, a, None) if il: if not isinstance(il, (tuple, list)): il = (il, ) for l in il: l = copy.copy(l) l.y1 += iy l.y2 += iy l.x1 += x1 l.x2 += x2 aS(l) x = xn y = yd leadingMove = 2 * y0 - y - thisy if dividerLines: xd = thisx + dx + dxTextSpace + jOffs[-1] + dividerOffsX[1] yd = thisy + dy * 0.5 + dividerOffsY if ((dividerLines & 1) and i % columnMaximum) or ( (dividerLines & 2) and not i % columnMaximum): g.add( Line(thisx + dividerOffsX[0], yd, xd, yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines & 4) and (i % columnMaximum == lim or i == (n - 1)): yd -= max(deltay, leadingMove) + yGap g.add( Line(thisx + dividerOffsX[0], yd, xd, yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... if isAuto(col): chart = getattr(col, 'chart', getattr(col, 'obj', None)) c = chart.makeSwatchSample(getattr(col, 'index', i), x, thisy, dx, dy) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): c = uSymbol2Symbol(swatchMarker, x + dx / 2., thisy + dy / 2., col) else: c = self._defaultSwatch(x, thisy, dx, dy, fillColor=col, strokeWidth=strokeWidth, strokeColor=strokeColor) elif col is not None: try: c = copy.deepcopy(col) c.x = x c.y = thisy c.width = dx c.height = dy except: c = None else: c = None if c: g.add(c) if scallout: scallout(self, g, thisx, y0, i, (col, name), c) for s in S: g.add(s) if self.colEndCallout and (i % columnMaximum == lim or i == (n - 1)): if alignment == "left": xt = thisx else: xt = thisx + dx + dxTextSpace yd = thisy + dy * 0.5 + dividerOffsY - ( max(deltay, leadingMove) + yGap) self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1] + dx + dxTextSpace) if i % columnMaximum == lim: if variColumn: thisx += jOffs[-1] + xW else: thisx = thisx + deltax thisy = upperlefty else: thisy = thisy - max(deltay, leadingMove) - yGap return g
def alpdf(mensaje): locale.getlocale() aux = mensaje.split('#') periodos = aux[0][2:-4].split(",") descriptores = aux [1][4:-2].split(",") #valor = int(descriptores[0]) #print("valor:",valor) #año = int(años_final[0][1:-1]) #print("descriptores: ",descriptores) #print("periodos ",periodos) doc = SimpleDocTemplate("SURALUM.pdf", pagesize=letter) story = [] imagen = Image(logotipo, 7 * cm, 3 * cm) story.append(imagen) story.append(Spacer(10, 20)) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) if (int(descriptores[0])):#VENTAS TOTALES print("ventas_totales") story.append(Paragraph('Ventas Totales por Año', styles['title'])) totales = [] connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: print() cursor = connection_ddbb.cursor() cursor.execute("SELECT id_venta, total, fecha FROM ventas WHERE EXTRACT(YEAR FROM fecha) = " + i) total = 0 for fname in cursor: total = total+ fname[1] #print ("Values:", fname[1]) totales.append(total) arreglo = [periodos,totales] table = Table(arreglo, colWidths=4* cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(arreglo): ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(table) d = Drawing(300, 200) data = [totales] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 400 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 1000000000 bc.valueAxis.valueStep = 100000000 #paso de distancia entre punto y punto bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = periodos bc.groupSpacing = 10 bc.barSpacing = 4 bc.barLabelFormat = '$%d' bc.valueAxis.labelTextFormat = ' $%d ' bc.barLabels.nudge = 7 d.add(bc) #pprint.pprint(bc.getProperties()) story.append(d) #print(story) ############################################################################################################################################################# if (int(descriptores[2][1:])): print("ventas por familia") story.append(Paragraph('Ventas por Familia', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() totales = [('Periodo','Suralum','Huracan','Industrial')] valores_g = [] for i in periodos: cursor.execute("""SELECT productos.id_familia, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos INNER JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND(productos.id_familia=1 OR productos.id_familia=2 OR productos.id_familia=3) GROUP BY productos.id_familia ORDER BY productos.id_familia DESC """) vt=[(i)] vg =[] for valor in cursor: #print ("Values:", valor) vt.append(valor[1]) vg.append(valor[1]) #print(vt) totales.append(vt) valores_g.append(vg) table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray), ('BACKGROUND', (0, 0), (0,-1), colors.gray) ]) story.append(table) d = Drawing(600, 200) data = valores_g bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 400 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 500000000 bc.valueAxis.valueStep = 100000000 #paso de distancia entre punto y punto bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = ('Suralum','Huracan','Industrial') bc.valueAxis.labelTextFormat = ' $%d ' bc.groupSpacing = 10 bc.barSpacing = 4 bc.barLabelFormat = '$%d' bc.barLabels.nudge = 7 legend=Legend() legend.x = 20 legend.y = 0 legend.boxAnchor = 'se' legend.subCols[1].align = 'right' legend.alignment = 'right' legend.columnMaximum = 9 legend.fontSize = 13 # these data can be read from external sources legend.colorNamePairs=Auto(obj=bc) d.add(bc) d.add(legend) #pprint.pprint(bc.getProperties()) story.append(d) #print(totales) if (int(descriptores[3][1:])): print("Suralum") story.append(Paragraph('Ventas Suralum', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: #print("para el periodo:",i) cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=1 GROUP BY productos.descripcion ORDER BY v DESC""") #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 12): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.green ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) ############################################################################################################################ if (int(descriptores[4][1:])): print("Huracan") story.append(Paragraph('Ventas Huracan', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: #print("para el periodo:",i) cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=2 GROUP BY productos.descripcion ORDER BY v DESC""") #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 12): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.violet ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) ####################################################################################################################################### if (int(descriptores[5][1:])): print("Industrial") story.append(Paragraph('Ventas Industrial', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: #print("para el periodo:",i) cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=3 GROUP BY productos.descripcion ORDER BY v DESC""") #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 12): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.aqua ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) if (int(descriptores[6][1:])): print("mas vendido") story.append(Paragraph('PRODUCTOS MÁS VENDIDOS', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+""" GROUP BY productos.descripcion ORDER BY v DESC""" ) story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 20): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas #producto.append(valor[3])#familia totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.aqua ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) doc.build(story)
def __init__(self, series_colors_cmyk, box_width, box_height, chart_width, chart_height, width=550, height=215, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) Drawing.hAlign = 'CENTER' font_name = 'Helvetica' # self.width = 550 # self.height = 240 self.width = box_width self.height = box_height self._add(self, LinePlot(), name='chart', validate=None, desc=None) self._add(self, LineLegend(), name='legend', validate=None, desc=None) # self.chart.width = 490 # self.chart.height = 150 self.chart.width = chart_width self.chart.height = chart_height self.chart.y = 60 self.chart.x = 45 self.chart.strokeWidth = 1 for color in series_colors_cmyk: index = series_colors_cmyk.index(color) self.chart.lines[index].strokeColor = PCMYKColor(color[0], color[1], color[2], color[3], alpha=color[4]) self.chart.lines[index].symbol = makeMarker('FilledCircle') self.chart.lines[index].symbol.strokeColor = PCMYKColor( color[0], color[1], color[2], color[3], alpha=color[4]) self.chart.lines[index].symbol.size = 5 self.chart.lines.strokeWidth = 2 self.legend.colorNamePairs = Auto(obj=self.chart) self.legend.x = 5 self.legend.y = 30 # set size of swatches self.legend.dx = 0 self.legend.dy = 0 self.legend.fontName = font_name self.legend.fontSize = 8 self.legend.alignment = 'right' self.legend.columnMaximum = 2 self.legend.dxTextSpace = 4 self.legend.variColumn = 1 self.legend.boxAnchor = 'nw' self.legend.deltay = 15 self.legend.autoXPadding = 20 self.background = Rect(0, 0, self.width, self.height, strokeWidth=0, fillColor=PCMYKColor(0, 0, 10, 0)) self.background.strokeColor = black self.background.fillOpacity = 0.25 self.background.strokeWidth = 0 self.background.x = 0 self.background.fillColor = PCMYKColor(16, 12, 13, 0, alpha=30)
def __init__(self, width=403, height=163, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) fontName = 'msyh' fontSize = 5 bFontName = 'Times-Bold' bFontSize = 7 colorsList = [ PCMYKColor(0, 73, 69, 56), PCMYKColor(0, 3, 7, 6), PCMYKColor(41, 25, 0, 21) ] self._add(self, VerticalBarChart(), name='chart', validate=None, desc=None) self.chart.height = 73 self.chart.fillColor = None self.chart.data = [[ 7.7199999999999998, 7.9400000000000004, 9.1699999999999999, 7.04, 7.7199999999999998, 8.1699999999999999 ], [4.46, 1.97, 13.220000000000001, 10.49, 8.5800000000000001, 10.74], [ 5.1399999999999997, 9.5999999999999996, 5.3099999999999996, 4.4699999999999998, 3.5099999999999998, 4.8399999999999999 ]] #self.chart.bars.fillColor = color self.chart.bars.strokeWidth = 0.5 self.chart.bars.strokeColor = PCMYKColor(0, 0, 0, 100) #self.chart.barLabels.angle = 90 #self.chart.barLabelFormat = DecimalFormatter(2) #self.chart.barLabels.boxAnchor ='w' #self.chart.barLabels.boxFillColor = None #self.chart.barLabels.boxStrokeColor= None #self.chart.barLabels.fontName = fontName #self.chart.barLabels.fontSize = fontSize #self.chart.barLabels.dy = 3 #self.chart.barLabels.boxTarget = 'hi' #self.chart.annotations=[lambda c,cA,vA: Line(c.x,c.y,c.x+c.width,c.y,strokeColor=black,strokeWidth=0.5)] for i, color in enumerate(colorsList): self.chart.bars[i].fillColor = color self.chart.valueAxis.labels.fontName = fontName self.chart.valueAxis.labels.fontSize = fontSize self.chart.valueAxis.strokeDashArray = (5, 0) self.chart.valueAxis.visibleGrid = True self.chart.valueAxis.visibleTicks = False self.chart.valueAxis.tickLeft = 0 self.chart.valueAxis.tickRight = 11 #self.chart.valueAxis.gridStrokeDashArray = (0,1,0) #self.chart.valueAxis.valueStep = 200 self.chart.valueAxis.strokeWidth = 0.25 #self.chart.valueAxis.gridStrokeWidth = 0.25 #self.chart.valueAxis.gridStrokeDashArray = (1,1,1) self.chart.valueAxis.avoidBoundFrac = 0 #1#0.5 self.chart.valueAxis.rangeRound = 'both' self.chart.valueAxis.gridStart = 13 self.chart.valueAxis.gridEnd = 342 self.chart.valueAxis.labelTextFormat = None #DecimalFormatter(1, suffix=None, prefix=None) self.chart.valueAxis.forceZero = True self.chart.valueAxis.labels.boxAnchor = 'e' self.chart.valueAxis.labels.dx = -1 self.chart.categoryAxis.strokeDashArray = (5, 0) #self.chart.categoryAxis.gridStrokeDashArray = (1,1,1) self.chart.categoryAxis.visibleGrid = False self.chart.categoryAxis.visibleTicks = False self.chart.categoryAxis.strokeWidth = 0.25 self.chart.categoryAxis.tickUp = 5 self.chart.categoryAxis.tickDown = 0 self.chart.categoryAxis.labelAxisMode = 'low' self.chart.categoryAxis.labels.textAnchor = 'end' self.chart.categoryAxis.labels.angle = 0 self.chart.categoryAxis.labels.fontName = bFontName self.chart.categoryAxis.labels.fontSize = bFontSize #self.chart.categoryAxis.tickShift = 1 #self.chart.categoryAxis.strokeDashArray = (0,1,0) # self.chart.categoryAxis.labels.boxAnchor = 'autox' self.chart.categoryAxis.labels.boxAnchor = 'e' self.chart.categoryAxis.labels.dx = 7 #-10 self.chart.categoryAxis.labels.dy = -5 self._add(self, Legend(), name='legend', validate=None, desc=None) self.legend.deltay = 8 self.legend.fontName = fontName self.legend.fontSize = fontSize self.legend.strokeWidth = 0.5 self.legend.strokeColor = PCMYKColor(0, 0, 0, 100) self.legend.autoXPadding = 0 self.legend.dy = 5 self.legend.variColumn = True self.legend.subCols.minWidth = self.chart.width / 2 # 175 self.legend.colorNamePairs = Auto(obj=self.chart) # self._add(self,TableWidget(),name='table',validate=None,desc=None) # self.table.x = 0 # self.table.y = 0 # self.table.height = 45 # self.table.borderStrokeColor = PCMYKColor(0, 12, 24, 36) # self.table.fillColor = PCMYKColor(0, 3, 7, 6) # self.table.borderStrokeWidth = 0.5 # self.table.horizontalDividerStrokeColor = PCMYKColor(0, 12, 24, 36) # self.table.verticalDividerStrokeColor = None # self.table.horizontalDividerStrokeWidth = 0.5 # self.table.verticalDividerStrokeWidth = 0 # self.table.dividerDashArray = None table_data = [[ 'BP', None, '7.72', '7.94', '9.17', '7.04', '7.72', '8.17' ], [ 'Shell Transport & Trading', None, '4.46', '1.97', '13.22', '10.49', '8.58', '10.74' ], [ 'Liberty International', None, '5.14', '9.60', '5.31', '4.47', '3.51', '4.84' ]] # self.table.boxAnchor = 'sw' # self.table.fontName = bFontName # self.table.fontSize = bFontSize # self.table.fontColor = colors.black # self.table.alignment = 'left' # self.table.textAnchor = 'start' for i in range(len(self.chart.data)): self.chart.bars[i].name = table_data[i][0] self.chart.categoryAxis.categoryNames = [ '200%d' % i for i in range(1, 7) ] self.width = 400 # self.table.width = 400 self.height = 200 self.legend.dx = 8 self.legend.dxTextSpace = 5 self.legend.deltax = 0 self.legend.alignment = 'right' self.legend.columnMaximum = 3 self.chart.y = 75 self.chart.barWidth = 2 self.chart.groupSpacing = 5 self.chart.width = 250 self.chart.barSpacing = 0.5 self.chart.x = 140 self.legend.y = 75 self.legend.boxAnchor = 'sw' self.legend.x = 24 self.chart.bars[0].fillColor = PCMYKColor(100, 60, 0, 50, alpha=100) self.chart.bars[1].fillColor = PCMYKColor(23, 51, 0, 4, alpha=100) self.chart.bars[2].fillColor = PCMYKColor(100, 0, 90, 50, alpha=100)
def __init__(self, width=400, height=200, *args, **kw): apply(Drawing.__init__, (self, width, height) + args, kw) self._add(self, VerticalBarChart(), name='bar', validate=None, desc=None) self.bar.data = [[4.22], [4.12], [3.65], [3.56], [3.49], [3.44], [3.07], [2.84], [2.76], [1.09]] self.bar.categoryAxis.categoryNames = [ 'Financials艰', 'Energy', 'Health Care', 'Telecoms', 'Consumer', 'Consumer 2', 'Industrials', 'Materials', 'Other', 'Liquid Assets' ] self.bar.categoryAxis.labels.fillColor = None self.bar.width = 200 self.bar.height = 150 self.bar.x = 30 self.bar.y = 15 self.bar.barSpacing = 5 self.bar.groupSpacing = 5 self.bar.valueAxis.labels.fontName = 'msyh' self.bar.valueAxis.labels.fontSize = 8 self.bar.valueAxis.forceZero = 1 self.bar.valueAxis.rangeRound = 'both' self.bar.valueAxis.valueMax = None #10# self.bar.categoryAxis.visible = 1 self.bar.categoryAxis.visibleTicks = 0 self.bar.barLabels.fontSize = 6 self.bar.valueAxis.labels.fontSize = 6 self.bar.strokeWidth = 0.1 self.bar.bars.strokeWidth = 0.5 n = len(self.bar.data) #add and set up legend self._add(self, Legend(), name='legend', validate=None, desc=None) _ = [ 'Vodafone Group', 'UBS', 'British Petroleum', 'Royal bk of Scotland', 'HSBC Holdings', 'Total Elf Fina', 'Repsol', 'Novartis', 'BNP Paribas', 'Schneider Electric' ] self.legend.colorNamePairs = [(Auto(chart=self.bar), (t, '%.2f' % d[0])) for t, d in zip(_, self.bar.data)] self.legend.columnMaximum = 10 self.legend.fontName = 'msyh' self.legend.fontSize = 5.5 self.legend.boxAnchor = 'w' self.legend.x = 260 self.legend.y = self.height / 2 self.legend.dx = 8 self.legend.dy = 8 self.legend.alignment = 'right' self.legend.yGap = 0 self.legend.deltay = 11 self.legend.dividerLines = 1 | 2 | 4 self.legend.subCols.rpad = 10 self.legend.dxTextSpace = 5 self.legend.strokeWidth = 0 self.legend.dividerOffsY = 6 self.legend.colEndCallout = TotalAnnotator( rText='%.2f' % sum([x[0] for x in self.bar.data]), fontName='Helvetica-Bold', fontSize=self.legend.fontSize * 1.1) self.legend.colorNamePairs = [ (self.bar.bars[i].fillColor, (self.bar.categoryAxis.categoryNames[i][0:20], '%0.2f' % self.bar.data[i][0])) for i in range(len(self.bar.data)) ] print self.legend.colorNamePairs
def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self,'swatchMarker',None) if isAuto(swatchMarker): chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor leading = fontSize*1.2 yGap = self.yGap if not deltay: deltay = max(dy,leading)+self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxWidth(colorNamePairs) nCols = int((n+columnMaximum-1)/columnMaximum) xW = dx+dxTextSpace+self.autoXPadding variColumn = self.variColumn if variColumn: width = reduce(operator.add,maxWidth,0)+xW*(nCols-1) else: deltax = max(maxWidth+xW,deltax) width = maxWidth+(nCols-1)*deltax maxWidth = nCols*[maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne','n','nw','autoy'): height = self._calcHeight() if ba in ('e','c','w'): thisy += height/2. else: thisy += height if ba not in ('nw','w','sw','autox'): if ba in ('n','c','s'): thisx -= width/2 else: thisx -= width upperlefty = thisy g = Group() def gAdd(t,g=g,fontName=fontName,fontSize=fontSize,fillColor=fillColor): t.fontName = fontName t.fontSize = fontSize t.fillColor = fillColor return g.add(t) ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self,'callout',None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in xrange(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) T = _getLines(name) S = [] j = int(i/columnMaximum) # thisy+dy/2 = y+leading/2 y = y0 = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,(col,name)) if alignment == "left": if isSeqType(name): for t in T[0]: S.append(String(thisx,y,t,fontName=fontName,fontSize=fontSize,fillColor=fillColor, textAnchor = "start")) y -= leading yd = y y = y0 for t in T[1]: S.append(String(thisx+maxWidth[j],y,t,fontName=fontName,fontSize=fontSize,fillColor=fillColor, textAnchor = "end")) y -= leading y = min(yd,y) else: for t in T: # align text to left S.append(String(thisx+maxWidth[j],y,t,fontName=fontName,fontSize=fontSize,fillColor=fillColor, textAnchor = "end")) y -= leading x = thisx+maxWidth[j]+dxTextSpace elif alignment == "right": if isSeqType(name): y0 = y for t in T[0]: S.append(String(thisx+dx+dxTextSpace,y,t,fontName=fontName,fontSize=fontSize,fillColor=fillColor, textAnchor = "start")) y -= leading yd = y y = y0 for t in T[1]: S.append(String(thisx+dx+dxTextSpace+maxWidth[j],y,t,fontName=fontName,fontSize=fontSize,fillColor=fillColor, textAnchor = "end")) y -= leading y = min(yd,y) else: for t in T: # align text to right S.append(String(thisx+dx+dxTextSpace,y,t,fontName=fontName,fontSize=fontSize,fillColor=fillColor, textAnchor = "start")) y -= leading x = thisx else: raise ValueError, "bad alignment" leadingMove = 2*y0-y-thisy if dividerLines: xd = thisx+dx+dxTextSpace+maxWidth[j]+dividerOffsX[1] yd = thisy+dy*0.5+dividerOffsY if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): yd -= max(deltay,leadingMove)+yGap g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... if isAuto(col): chart = getattr(col,'chart',getattr(col,'obj',None)) g.add(chart.makeSwatchSample(getattr(col,'index',i),x,thisy,dx,dy)) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): g.add(uSymbol2Symbol(swatchMarker,x+dx/2.,thisy+dy/2.,col)) else: g.add(self._defaultSwatch(x,thisy,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor)) else: try: c = copy.deepcopy(col) c.x = x c.y = thisy c.width = dx c.height = dy g.add(c) except: pass map(gAdd,S) if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): if alignment == "left": xt = thisx else: xt = thisx+dx+dxTextSpace yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) self.colEndCallout(self, g, thisx, xt, yd, maxWidth[j], maxWidth[j]+dx+dxTextSpace) if i%columnMaximum==lim: if variColumn: thisx += maxWidth[j]+xW else: thisx = thisx+deltax thisy = upperlefty else: thisy = thisy-max(deltay,leadingMove)-yGap return g
def create_bar(self, data_list, label_x_axis, contain, y_label=None, x_label=None, bar_width=520, bar_height=100, draw_width=520, draw_height=200, user_color=None, fontName="Times-Roman", fontSize=6, x_angle=0, bar_space=0): d = Drawing(width=draw_width, height=draw_height) bar = VerticalBarChart() bar.width = bar_width bar.height = bar_height bar.y = bar.height - (bar_height / 4) bar.strokeColor = colors.black bar.barLabelFormat = '%s' bar.barLabels.nudge = 7 bar.barLabels.fontSize = fontSize ################# X AXIS PROPERTIES ################# bar.categoryAxis.labels.dx = 0 bar.categoryAxis.labels.angle = x_angle bar.categoryAxis.labels.boxAnchor = 'autox' bar.categoryAxis.labels.fontSize = fontSize bar.categoryAxis.labels.fontName = self.master_font bar.categoryAxis.strokeWidth = 0.25 bar.categoryAxis.tickDown = -(bar.height) bar.categoryAxis.categoryNames = label_x_axis labX = Label() labX.boxAnchor = 'ne' labX.dx = bar.width * 2.15 labX.dy = bar.height labX.fontName = fontName labX.fontSize = fontSize labX.setText(x_label) d.add(labX) ##################################################### ################# Y AXIS PROPERTIES ################# bar.valueAxis.forceZero = 1 bar.valueAxis.labels.fontSize = fontSize bar.valueAxis.labels.fontName = fontName bar.valueAxis.rangeRound = 'both' bar.valueAxis.valueMin = 0 bar.valueAxis.visibleGrid = 1 bar.valueAxis.visibleAxis = 1 bar.valueAxis.labels.dx = -10 labY = Label() labY.boxAnchor = 'autox' labY.dy = bar.y + (bar.height / 1.5) labY.dx = bar.x - 30 labY.angle = 90 labY.fontName = fontName labY.fontSize = fontSize labY.setText(y_label) d.add(labY) ##################################################### bar.barSpacing = bar_space # bar.groupSpacing = 3 bar.data = data_list # print len(data_list) # print len(contain) if user_color != None: usage_color = user_color else: random_range = [randint(0, 100) for i in range(len(contain))] usage_color = map( lambda item: PCMYKColor(randint(0, item), randint(0, item), randint(0, item), randint(0, item)), random_range) for i in range(len(data_list)): bar.bars[i].name = contain[i].upper() bar.bars[i].fillColor = usage_color[i] legend = Legend() # legend.autoXPadding = 10 legend.alignment = 'right' legend.boxAnchor = 'sw' legend.dxTextSpace = 10 legend.fontSize = fontSize legend.fontName = fontName legend.subCols.minWidth = 55 legend.variColumn = 1 legend.deltay = 15 legend.x = bar.x legend.colorNamePairs = Auto(obj=bar) d.add(bar) d.add(legend) self.flowables.append(d)
def __init__(self, width=298, height=164, *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 self.chart.height = height # chart bars self.chart.bars.strokeColor = None self.chart.bars.strokeWidth = 0 self.chart.barSpacing = 4 self.chart.barWidth = 14 self.chart.barLabelFormat = '%s' self.chart.barLabels.nudge = 5 self.chart.barLabels.fontName = fontName self.chart.barLabels.fontSize = 5 # categoy axis self.chart.categoryAxis.labelAxisMode = 'low' self.chart.categoryAxis.labels.angle = 0 self.chart.categoryAxis.labels.boxAnchor = 'n' self.chart.categoryAxis.labels.dy = -6 self.chart.categoryAxis.labels.fillColor = PCMYKColor(0, 0, 0, 100) self.chart.categoryAxis.labels.fontName = fontName self.chart.categoryAxis.labels.fontSize = 8 self.chart.categoryAxis.labels.textAnchor = 'middle' self.chart.categoryAxis.tickShift = 1 self.chart.categoryAxis.visibleTicks = 0 self.chart.categoryAxis.strokeWidth = 0 self.chart.categoryAxis.strokeColor = None self.chart.groupSpacing = 15 # value axis self.chart.valueAxis.avoidBoundFrac = None self.chart.valueAxis.labels.fontName = fontName self.chart.valueAxis.labels.fontSize = 8 self.chart.valueAxis.rangeRound = 'both' self.chart.valueAxis.strokeWidth = 0 self.chart.valueAxis.visibleGrid = 1 self.chart.valueAxis.visibleTicks = 0 self.chart.valueAxis.visibleAxis = 0 self.chart.valueAxis.gridStrokeColor = PCMYKColor(100, 0, 46, 46) self.chart.valueAxis.gridStrokeWidth = 0.25 self.chart.valueAxis.valueStep = None #3 self.chart.valueAxis.labels.dx = -3 # legend self._add(self, Legend(), name='legend', validate=None, desc=None) self.legend.alignment = 'right' self.legend.boxAnchor = 'sw' self.legend.columnMaximum = 3 self.legend.dx = 8 self.legend.dxTextSpace = 4 self.legend.dy = 6 self.legend.fontSize = 8 self.legend.fontName = fontName self.legend.strokeColor = None self.legend.strokeWidth = 0 self.legend.subCols.minWidth = 55 self.legend.variColumn = 1 self.legend.y = 1 self.legend.deltay = 10 self.legend.colorNamePairs = Auto(obj=self.chart) self.legend.autoXPadding = 65 # x label self._add(self, Label(), name='XLabel', validate=None, desc="The label on the horizontal axis") self.XLabel._text = "" self.XLabel.fontSize = 6 self.XLabel.height = 0 self.XLabel.maxWidth = 100 self.XLabel.textAnchor = 'middle' self.XLabel.x = 0 self.XLabel.y = 10 # y label # self._add(self,Label(),name='YLabel',validate=None,desc="The label on the vertical axis") # self.YLabel._text = "" # self.YLabel.angle = 90 # self.YLabel.fontSize = 6 # self.YLabel.height = 0 # self.YLabel.maxWidth = 100 # self.YLabel.textAnchor ='middle' # self.YLabel.x = 12 # self.YLabel.y = 0 #sample data self.chart.data = [[ -2.6000000000000001, -0.80000000000000004, 9.8000000000000007, None, None, None, None ], [ -1.8999999999999999, 1.3999999999999999, 13.1, None, None, None, None ], [ -1.8999999999999999, 1.3, 12.199999999999999, 4.9000000000000004, 2.2000000000000002, 5.4000000000000004, 10.6 ], [ -1.7, 2.0, 13.300000000000001, 5.9000000000000004, 3.2000000000000002, 6.4000000000000004, 11.6 ], [ -1.8999999999999999, 1.5, 13.9, 4.0999999999999996, -1.3, 3.8999999999999999, 11.1 ]] self.chart.categoryAxis.categoryNames = [ 'Q3', 'YTD', '1 Year', '3 Year', '5 Year', '7 Year', '10 Year' ] for i in range(len(self.chart.data)): self.chart.bars[i].name = ( 'BP妈', 'Shell Transport & Trading', 'Liberty International', 'Persimmon', 'Royal Bank of Scotland', )[i] self.width = 400 self.height = 200 self.chart.x = 30 self.chart.y = 65 self.legend.x = 30 self.chart.bars[0].fillColor = PCMYKColor(0, 100, 100, 40, alpha=85) self.chart.bars[1].fillColor = PCMYKColor(23, 51, 0, 4, alpha=85) self.chart.bars[2].fillColor = PCMYKColor(100, 60, 0, 50, alpha=85) self.chart.bars[3].fillColor = PCMYKColor(66, 13, 0, 22, alpha=85) self.chart.bars.fillColor = PCMYKColor(100, 0, 90, 50, alpha=85)
def __init__(self, data, font, font_bold, title, x_axis_params, y_axis_params, series_names, series_colors_cmyk, box_width, box_height, chart_width, chart_height, width=550, height=215, *args, **kw): logger.debug("Generating line chart with data:\n{0}\n".format( json.dumps(data, indent=2))) Drawing.__init__(self, width, height, *args, **kw) Drawing.hAlign = "CENTER" # self.width = 550 # self.height = 240 self.width = box_width self.height = box_height self._add(self, LinePlot(), name="chart", validate=None, desc=None) self._add(self, LineLegend(), name="legend", validate=None, desc=None) # self.chart.width = 490 # self.chart.height = 150 self.chart.width = chart_width self.chart.height = chart_height self.chart.y = 60 self.chart.x = 45 self.chart.strokeWidth = 1 for color in series_colors_cmyk: index = series_colors_cmyk.index(color) self.chart.lines[index].strokeColor = PCMYKColor(color[0], color[1], color[2], color[3], alpha=color[4]) self.chart.lines[index].symbol = makeMarker("FilledCircle") self.chart.lines[index].symbol.strokeColor = PCMYKColor( color[0], color[1], color[2], color[3], alpha=color[4]) self.chart.lines[index].symbol.size = 5 self.chart.lines.strokeWidth = 2 self.legend.colorNamePairs = Auto(obj=self.chart) self.legend.x = 10 * ( len(series_names) // 5 ) # adjust how far to the left/right the legend labels are self.legend.y = 12 * (len(series_names) // 5 ) # adjust how far up/down the legend labels are # set size of swatches self.legend.dx = 0 self.legend.dy = -5 self.legend.fontName = font self.legend.fontSize = 100 // len(series_names) self.legend.alignment = "right" self.legend.columnMaximum = ( len(series_names) // 5) + 1 # adjust number of ROWS allowed in legend self.legend.dxTextSpace = 4 self.legend.variColumn = 1 self.legend.boxAnchor = "nw" self.legend.deltay = 10 # adjust the space between legend rows self.legend.autoXPadding = 15 * ( (len(series_names) // 5) + 1 ) # adjust the space between legend columns self.background = Rect(0, 0, self.width, self.height, strokeWidth=0, fillColor=PCMYKColor(0, 0, 10, 0)) self.background.strokeColor = black self.background.fillOpacity = 0.25 self.background.strokeWidth = 0 self.background.x = 0 self.background.fillColor = PCMYKColor(16, 12, 13, 0, alpha=30) self.make_title(title, font=font_bold) self.make_data(data) self.make_x_axis(*x_axis_params, font=font) self.make_y_axis(*y_axis_params, font=font) self.make_series_labels(series_names)
def createGraphics(self, data, categoryNames, file): self.bar.data = data self.bar.categoryAxis.categoryNames = categoryNames self.bar.categoryAxis.labels.fillColor = None self.bar.width = 160 self.bar.height = 100 self.bar.x = 30 self.bar.y = 15 self.bar.barSpacing = 5 self.bar.groupSpacing = 5 self.bar.valueAxis.labels.fontName = 'Helvetica' self.bar.valueAxis.labels.fontSize = 6 self.bar.valueAxis.forceZero = 1 self.bar.valueAxis.rangeRound = 'both' self.bar.valueAxis.valueMax = None #10# self.bar.categoryAxis.visible = 1 self.bar.categoryAxis.visibleTicks = 0 self.bar.barLabels.fontSize = 6 self.bar.valueAxis.labels.fontSize = 6 self.bar.strokeWidth = 0.1 self.bar.bars.strokeWidth = 0.5 n = len(self.bar.data) setItems(n, self.bar.bars, 'fillColor', pdf_chart_colors) #add and set up legend self._add(self, Legend(), name='legend', validate=None, desc=None) _ = [ 'Vodafone Group', 'UBS', 'British Petroleum', 'Royal bk of Scotland', 'HSBC Holdings', 'Total Elf Fina', 'Repsol', 'Novartis', 'BNP Paribas', 'Schneider Electric' ] self.legend.colorNamePairs = [(Auto(chart=self.bar), (t, '%.2f' % d[0])) for t, d in zip(_, self.bar.data)] self.legend.columnMaximum = 10 self.legend.fontName = 'Helvetica' self.legend.fontSize = 5.5 self.legend.boxAnchor = 'w' self.legend.x = 200 self.legend.y = self.height / 4 self.legend.dx = 8 self.legend.dy = 8 self.legend.alignment = 'right' self.legend.yGap = 0 self.legend.deltay = 11 self.legend.dividerLines = 1 | 2 | 4 self.legend.subCols.rpad = 10 self.legend.dxTextSpace = 3 self.legend.strokeWidth = 0 self.legend.dividerOffsY = 6 self.legend.colEndCallout = TotalAnnotator( rText='%.2f' % sum([x[0] for x in self.bar.data]), fontName='Helvetica-Bold', fontSize=self.legend.fontSize * 1.1) self.legend.colorNamePairs = [ (self.bar.bars[i].fillColor, (self.bar.categoryAxis.categoryNames[i][0:20], '%0.2f' % self.bar.data[i][0])) for i in range(len(self.bar.data)) ] self.save( formats=['pdf'], outDir='graphics/' + file, fnRoot=None, ) # if __name__=="__main__": #NORUNTESTS # drawing = FactSheetHoldingsVBar() # drawing.save(formats=['pdf'],outDir='.',fnRoot=None,) # #drawing.save(formats=['png'],outDir='.',fnRoot=None)