def drawing_chinese(): from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.charts.textlabels import Label from reportlab.graphics import renderPDF from reportlab.graphics.widgets.markers import makeMarker data = [((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)), ((1, 50), (2, 80), (3, 400), (4, 40), (5, 70))] drawing = Drawing(500, 300) lp = LinePlot() lp.x = 50 #������������ lp.y = 30 lp.height = 250 lp.width = 400 lp.data = data lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.xValueAxis.valueMin = 1 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 500 lp.yValueAxis.valueStep = 100 drawing.add(lp) title = Label() #����Ҫ��ʾ���ģ���Ҫ��ע��һ���������� title.fontName = "msyh" title.fontSize = 12 title_text = u'你好吗' #title_text = "abc" title._text = title_text title.x = 250 title.y = 280 title.textAnchor = 'middle' drawing.add(title) Xlabel = Label() Xlabel._text = 'x' Xlabel.fontSize = 12 Xlabel.x = 480 Xlabel.y = 30 Xlabel.textAnchor = 'middle' drawing.add(Xlabel) Ylabel = Label() Ylabel._text = "y" Ylabel.fontSize = 12 Ylabel.x = 40 Ylabel.y = 295 Ylabel.textAnchor = 'middle' drawing.add(Ylabel) try: drawing.save(formats=['gif'], outDir=".", fnRoot="abc") except: import traceback traceback.print_exc()
def addChromosomes(drawing, chrNames, chrSizes, xmap, ymap, w=0.1*DPI, fillColor=colors.skyblue, strokeColor=colors.skyblue): for i,chrom in enumerate(chrNames): x = xmap(i+1) y = ymap(chrSizes[chrom]) h = ymap(1)-ymap(chrSizes[chrom]) chromosome = Rect(x,y,w,h, strokeColor=strokeColor, fillColor=fillColor) drawing.add(chromosome) topCap = Wedge(x+0.5*w, y+h, 0.5*w, 0, 180, strokeColor=strokeColor, fillColor=fillColor) bottomCap = Wedge(x+0.5*w, y, 0.5*w, 180, 0, strokeColor=strokeColor, fillColor=fillColor) drawing.add(topCap) drawing.add(bottomCap) label = Label() label.setOrigin(xmap(i+1)+w/2, ymap(0)) label.boxAnchor = 's' label.textAnchor = 'middle' label.dx = 0 label.dy = DPI/10 label.setText(chrom) label.fontSize = 36 label.fontName = 'Helvetica' drawing.add(label) chrLength = Label() chrLength.setOrigin(xmap(i+1)+w/2, ymap(chrSizes[chrom])) chrLength.boxAnchor = 'n' chrLength.textAnchor = 'middle' chrLength.dx = 0 chrLength.dy = -DPI/10 chrLength.setText('%iMb' % int(chrSizes[chrom]/1e6)) chrLength.fontSize = 24 chrLength.fontName = 'Helvetica' drawing.add(chrLength)
def _drawLabels(self, Title, xAxis, yAxis): self.graphCenterX = self.width/2 self.graphCenterY = self.height/2 Label_Xaxis = Label() Label_Xaxis.fontSize = 7 Label_Xaxis.angle = 0 Label_Xaxis.dx = self.graphCenterX - 50 Label_Xaxis.dy = 0 Label_Xaxis.boxAnchor = 's' Label_Xaxis.setText(xAxis) self.drawing.add(Label_Xaxis) Label_Yaxis = Label() Label_Yaxis.fontSize = 7 Label_Yaxis.angle = 90 Label_Yaxis.boxAnchor = 'n' Label_Yaxis.dx = -5 Label_Yaxis.dy = self.graphCenterY Label_Yaxis.setText(yAxis) self.drawing.add(Label_Yaxis) Label_Graph = Label() Label_Graph.fontSize = 10 Label_Graph.angle = 0 Label_Graph.boxAnchor = 'n' Label_Graph.dx = self.graphCenterX - 50 Label_Graph.dy = self.height Label_Graph.setText(Title) self.drawing.add(Label_Graph)
def add_findings_by_provider_chart(): drawing = Drawing(300, 200) data = get_findings_by_provider() maxVal = max(data[0]) 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 = 10 bar = HorizontalBarChart() bar.x = 30 bar.y = 0 bar.height = 100 bar.width = 400 bar.data = data bar.strokeColor = colors.white bar.valueAxis.valueMin = 0 bar.valueAxis.valueMax = maxVal * 2 ## graph displa twice as much as max violation bar.valueAxis.valueStep = value_step ## Convert to neartest 100 bar.categoryAxis.labels.boxAnchor = 'ne' bar.categoryAxis.labels.dx = -10 bar.categoryAxis.labels.dy = -2 bar.categoryAxis.labels.fontName = 'Helvetica' bar.categoryAxis.categoryNames = ["AWS", "Azure"] bar.bars[(0, 0)].fillColor = HexColor("#434476") bar.bars[(0, 1)].fillColor = HexColor("#B170DB") bar.barWidth = 3.5 bar.barSpacing = 0.1 bar.barLabelFormat = '%d' bar.barLabels.nudge = 15 bar.bars[0].strokeColor = None drawing.add(bar) # add_legend(drawing, bar) yLabel = Label() yLabel.setText("Number of Findings") yLabel.fontSize = 10 yLabel.fontName = 'Helvetica' yLabel.dx = 250 yLabel.dy = -30 chartLabel = Label() chartLabel.setText("Findings by Provider") chartLabel.fontSize = 10 chartLabel.fillColor = HexColor("#737373") chartLabel.fontName = 'Helvetica-Bold' chartLabel.dx = 250 chartLabel.dy = 160 drawing.add(chartLabel) drawing.add(yLabel) fields.append(drawing)
def addChromosomes(drawing, chrNames, chrSizes, xmap, ymap, w=0.1 * DPI, fillColor=colors.skyblue, strokeColor=colors.skyblue): for i, chrom in enumerate(chrNames): x = xmap(i + 1) y = ymap(chrSizes[chrom]) h = ymap(1) - ymap(chrSizes[chrom]) chromosome = Rect(x, y, w, h, strokeColor=strokeColor, fillColor=fillColor) drawing.add(chromosome) topCap = Wedge(x + 0.5 * w, y + h, 0.5 * w, 0, 180, strokeColor=strokeColor, fillColor=fillColor) bottomCap = Wedge(x + 0.5 * w, y, 0.5 * w, 180, 0, strokeColor=strokeColor, fillColor=fillColor) drawing.add(topCap) drawing.add(bottomCap) label = Label() label.setOrigin(xmap(i + 1) + w / 2, ymap(0)) label.boxAnchor = 's' label.textAnchor = 'middle' label.dx = 0 label.dy = DPI / 10 label.setText(chrom) label.fontSize = 36 label.fontName = 'Helvetica' drawing.add(label) chrLength = Label() chrLength.setOrigin(xmap(i + 1) + w / 2, ymap(chrSizes[chrom])) chrLength.boxAnchor = 'n' chrLength.textAnchor = 'middle' chrLength.dx = 0 chrLength.dy = -DPI / 10 chrLength.setText('%iMb' % int(chrSizes[chrom] / 1e6)) chrLength.fontSize = 24 chrLength.fontName = 'Helvetica' drawing.add(chrLength)
def draw_recent_week_pdf(filename, data_list): """ 画最近七天的流量计报表 :param filename: :param data_list :return: """ data = [] max_val = 0 for index in range(0, len(data_list)): data.append((index + 1, data_list[index])) max_val = max(max_val, data_list[index]) drawing = Drawing(500, 800) lp = LinePlot() lp.x = 50 lp.y = 80 lp.height = 600 lp.width = 400 lp.data = [data] lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.xValueAxis.valueMin = 1 lp.xValueAxis.valueMax = 7 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = (int(max_val / 100) + 1) * 100 lp.yValueAxis.valueStep = 100 drawing.add(lp) x_title = Label() # 若需要显示中文,需要先注册一个中文字体 pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc")) x_title.fontName = "haha" x_title.fontSize = 12 title_text = '用气量' x_title._text = title_text x_title.x = 20 x_title.y = 100 x_title.textAnchor = 'middle' drawing.add(x_title) y_title = Label() # 若需要显示中文,需要先注册一个中文字体 pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc")) y_title.fontName = "haha" y_title.fontSize = 12 title_text = '最近七天' y_title._text = title_text y_title.x = 80 y_title.y = 50 y_title.textAnchor = 'middle' drawing.add(y_title) drawing.save(formats=['pdf'], outDir=TMP_FILE_DIRECTORY_PATH, fnRoot=filename)
def getTalkRect(self, startTime, duration, trackId, text): "Return shapes for a specific talk" g = Group() y_bottom = self.scaleTime(startTime + duration) y_top = self.scaleTime(startTime) y_height = y_top - y_bottom if trackId is None: #spans all columns x = self._colLeftEdges[1] width = self.width - self._colWidths[0] else: #trackId is 1-based and these arrays have the margin info in column #zero, so no need to add 1 x = self._colLeftEdges[trackId] width = self._colWidths[trackId] lab = Label() lab.setText(text) lab.setOrigin(x + 0.5*width, y_bottom+0.5*y_height) lab.boxAnchor = 'c' lab.width = width lab.height = y_height lab.fontSize = 6 r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan) g.add(r) g.add(lab) #now for a label # would expect to color-code and add text return g
def addScale(drawing, xmap, y, start, end, tickLen=10, dx=3, dy=6, textAnchor='middle', boxAnchor='s', fontSize=12, strokeWidth=1, strokeColor=colors.black, scale=1.0, format='%ibp'): x1 = xmap(start) x2 = xmap(end) line = Line(x1+dx,y,x2-dx,y, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(line) leftTick = Line(x1+dx,y-0.5*tickLen,x1+dx,y+0.5*tickLen, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(leftTick) rightTick = Line(x2-dx,y-0.5*tickLen,x2-dx,y+0.5*tickLen, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(rightTick) label = Label() label.setOrigin(0.5*(x1+x2), y+dy) distance = float(end-start)/scale label.setText(format % (distance/scale)) label.fontSize = fontSize label.textAnchor = textAnchor label.boxAnchor = boxAnchor drawing.add(label)
def draw(self): # general widget bits w = float(self.length) h = float(self.height) g = shapes.Group() body = shapes.Polygon( [self.x-0.5*w, self.y-0.5*w, self.x-0.5*w, self.y+0.5*w, self.x+0.5*w, self.y], fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=self.strokeWidth) g.add(body) if self.label: b = g.getBounds() s = Label() s.setText(self.label) s.setOrigin(self.x+0.5*w, self.y-h/2+b[3]-b[1]+4) s.boxAnchor = self.boxAnchor s.textAnchor = self.textAnchor s.fontName = 'Helvetica' s.fontSize = self.fontSize s.angle = self.labelAngle g.add(s) return g
def graphout_stackedBar(data, labels, X, Y): drawing = Drawing(X*inch, Y*inch) bar = VerticalBarChart() bar.x = 50 bar.y = 50 bar.width = (X-2)*inch bar.height = (Y-1)*inch bar.data = data bar.bars.strokeWidth = 0 bar.categoryAxis.style='stacked' bar.categoryAxis.labels.boxAnchor = 'ne' bar.categoryAxis.labels.dx = -2 bar.categoryAxis.labels.dy = -2 bar.categoryAxis.labels.angle = 45 bar.categoryAxis.categoryNames = labels # ensure bar chart and legend coloring matches for i in range(len(data)): bar.bars[i].fillColor = colorList[i] # Create a title for the y-axis yLabel = Label() yLabel.setOrigin(0, 50) # for reference, the graph origin is (50, 50) yLabel.boxAnchor = 'c' yLabel.angle = 90 yLabel.setText('Data Storage [GB]') yLabel.fontSize=16 yLabel.dy = 1.25*inch drawing.add(yLabel) drawing.add(bar) return drawing
def _drawLabels(self, label, labelCenter, y, width): """ Draw the label given in a given area originating at (x,y) with width 'width' """ fontName = 'Times-Roman' fontSize = 10 #Limit the length of the label to the boundaries of the chartAreaWidth strWidth = self._stringWidth(label, fontName, fontSize) #Calculate the area taken by one character oneCharWidth = self._stringWidth(label[0], fontName, fontSize) #If the given string needs more size, reduce the string to a length which fits #in the given area if strWidth > width: maxPossibleLen = int(width/oneCharWidth) label = label[:maxPossibleLen] strWidth = self._stringWidth(label, fontName, fontSize) x = (labelCenter - ((strWidth)/2)) Label_Graph = Label() Label_Graph.fontName = fontName Label_Graph.fontSize = fontSize #Label_Graph.angle = 0 Label_Graph.boxAnchor = 'n' Label_Graph.x = x Label_Graph.y = y Label_Graph.setText(label) self.drawing.add(Label_Graph)
def getTalkRect(self, startTime, duration, trackId, text): "Return shapes for a specific talk" g = Group() y_bottom = self.scaleTime(startTime + duration) y_top = self.scaleTime(startTime) y_height = y_top - y_bottom if trackId is None: #spans all columns x = self._colLeftEdges[1] width = self.width - self._colWidths[0] else: #trackId is 1-based and these arrays have the margin info in column #zero, so no need to add 1 x = self._colLeftEdges[trackId] width = self._colWidths[trackId] lab = Label() lab.setText(text) lab.setOrigin(x + 0.5 * width, y_bottom + 0.5 * y_height) lab.boxAnchor = 'c' lab.width = width lab.height = y_height lab.fontSize = 6 r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan) g.add(r) g.add(lab) #now for a label # would expect to color-code and add text return g
def draw(self): ascent = getFont(self.xValueAxis.labels.fontName).face.ascent if ascent == 0: ascent = 0.718 # default (from helvetica) ascent = ascent * self.xValueAxis.labels.fontSize # normalize # basic LinePlot - does the Axes, Ticks etc lp = LinePlot.draw(self) xLabel = self.xLabel if xLabel: # Overall label for the X-axis xl = Label() xl.x = (self.x + self.width) / 2.0 xl.y = 0 xl.fontName = self.xValueAxis.labels.fontName xl.fontSize = self.xValueAxis.labels.fontSize xl.setText(xLabel) lp.add(xl) yLabel = self.yLabel if yLabel: # Overall label for the Y-axis yl = Label() yl.angle = 90 yl.x = 0 yl.y = self.y + self.height / 2.0 yl.fontName = self.yValueAxis.labels.fontName yl.fontSize = self.yValueAxis.labels.fontSize yl.setText(yLabel) lp.add(yl) # do a bounding box - in the same style as the axes if self.outerBorderOn: lp.add( Rect( self.x, self.y, self.width, self.height, strokeColor=self.outerBorderColor, strokeWidth=self.yValueAxis.strokeWidth, fillColor=None, ) ) lp.shift(self.leftPadding, self.bottomPadding) return lp
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 write_label(label, width, height, person): text = "\n".join((person['name'], person['addresses'][0])) lab = Label() lab.setOrigin(8, height - 5) lab.fontSize = 14 lab.setText(text) lab.boxAnchor = 'nw' label.add(lab)
def header_draw(self, x, y, text): chart_title = Label() chart_title.x = x chart_title.y = y chart_title.fontName = 'RobotoBold' chart_title.fontSize = 9 chart_title.textAnchor = 'middle' chart_title.setText(text) return chart_title
def title_draw(self, x, y, text): chart_title = Label() chart_title.x = x chart_title.y = y chart_title.fontName = 'FreeSansBold' chart_title.fontSize = 16 chart_title.textAnchor = 'middle' chart_title.setText(text) return chart_title
def draw(self): ascent = getFont(self.xValueAxis.labels.fontName).face.ascent if ascent == 0: ascent = 0.718 # default (from helvetica) ascent = ascent * self.xValueAxis.labels.fontSize # normalize #basic LinePlot - does the Axes, Ticks etc lp = LinePlot.draw(self) xLabel = self.xLabel if xLabel: #Overall label for the X-axis xl = Label() xl.x = (self.x + self.width) / 2.0 xl.y = 0 xl.fontName = self.xValueAxis.labels.fontName xl.fontSize = self.xValueAxis.labels.fontSize xl.setText(xLabel) lp.add(xl) yLabel = self.yLabel if yLabel: #Overall label for the Y-axis yl = Label() yl.angle = 90 yl.x = 0 yl.y = (self.y + self.height / 2.0) yl.fontName = self.yValueAxis.labels.fontName yl.fontSize = self.yValueAxis.labels.fontSize yl.setText(yLabel) lp.add(yl) # do a bounding box - in the same style as the axes if self.outerBorderOn: lp.add( Rect(self.x, self.y, self.width, self.height, strokeColor=self.outerBorderColor, strokeWidth=self.yValueAxis.strokeWidth, fillColor=None)) lp.shift(self.leftPadding, self.bottomPadding) return lp
def draw(self): # general widget bits w = float(self.length) h = float(self.height) # print self.label,w,h # Set minimum size if abs(w)<self.wmin: xmid = self.x+0.5*w w = w/abs(w) * self.wmin self.x = xmid-0.5*w g = shapes.Group() if abs(w)>self.wNoTail: # arrow specific bits body = shapes.Rect(x=self.x, y=self.y-self.aspectRatio*h/2, width=2*(w/3), height=self.aspectRatio*h, fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=self.strokeWidth) g.add(body) head = shapes.Polygon( points=[self.x+w, self.y, self.x+2*(w/3), self.y+h/2, self.x+2*(w/3), self.y-h/2, self.x+w, self.y], fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=self.strokeWidth) g.add(head) else: head = shapes.Polygon( points=[self.x+w, self.y, self.x, self.y+h/2, self.x, self.y-h/2, self.x+w, self.y], fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=self.strokeWidth) g.add(head) if self.label: b = g.getBounds() s = Label() s.setText(self.label) s.setOrigin(self.x+0.5*w+self.labeldx, self.y-h/2+b[3]-b[1]+self.labeldy) s.boxAnchor = self.boxAnchor s.textAnchor = self.textAnchor s.fontName = 'Helvetica' s.fontSize = self.fontSize s.angle = self.labelAngle g.add(s) return g
def setTitle(self): title = Label() title.fontName = 'Helvetica-Bold' title.fontSize = 12 title.x = 300 title.y = 335 title._text = self._data_dict.get('title', '') title.maxWidth = 180 title.height = 20 title.textAnchor ='middle' self.add(title, name='Title')
def setDescription(self): desc = Label() desc.fontName = 'Helvetica' desc.fontSize = 12 desc.x = 230 desc.y = 10 desc._text = self._data_dict.get('description', '') desc.maxWidth = 280 desc.height = 20 desc.textAnchor ='middle' self.add(desc, name='Description')
def cn_process(self, text, x, y, pathnow) : pdfmetrics.registerFont(ttfonts.TTFont("font1",'simsun.ttc')) title = Label() title.fontName = "font1" title.fontSize = 14 title_text = text title._text = title_text title.x = x title.y = y return (title)
def add_trends_open_findings_chart(): drawing = Drawing(300, 200) data, months = get_open_findings_trends() maxVal = max(data[0]) 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 lc = HorizontalLineChart() lc.x = 25 lc.y = 40 lc.height = 100 lc.width = doc.width lc.lines.symbol = makeMarker('Square') lc.joinedLines = 1 lc.data = data lc.categoryAxis.categoryNames = months lc.categoryAxis.labels.boxAnchor = 'c' # lc.categoryAxis.valueMin = months[0] lc.valueAxis.valueMin = 0 lc.valueAxis.valueStep = value_step lc.valueAxis.valueMax = max(data[0]) * 2 lc.lines[0].strokeColor = colors.green #lc.fillColor = colors.whitesmoke #lc.inFill = 1 #lc.categoryAxis.labels.dx = -20 #lc.categoryAxis.labels.dy = -10 lc.lineLabelFormat = "%d" chartLabel = Label() chartLabel.setText("Trends - Total Open Findings") chartLabel.fontSize = 10 chartLabel.fillColor = HexColor("#737373") chartLabel.fontName = 'Helvetica-Bold' chartLabel.dx = 250 chartLabel.dy = 160 drawing.add(chartLabel) drawing.add(lc) fields.append(drawing)
def addLabels(self,drawing,title=None,xlabel=None,ylabel=None): from reportlab.graphics.charts.textlabels import Label if not title is None: Title = Label() Title.fontName = 'Helvetica-Bold' Title.fontSize = 7 Title.x = drawing.width/2 Title.y = drawing.height-25 Title._text = title Title.maxWidth = 180 Title.height = 20 Title.textAnchor ='middle' drawing.add(Title) if not xlabel is None: XLabel = Label() XLabel.fontName = 'Helvetica' XLabel.fontSize = 7 XLabel.x = drawing.width/2 XLabel.y = 10 XLabel.textAnchor ='middle' XLabel.maxWidth = 100 XLabel.height = 20 XLabel._text = xlabel drawing.add(XLabel) if not ylabel is None: YLabel = Label() YLabel.fontName = 'Helvetica' YLabel.fontSize = 7 YLabel.x = 12 YLabel.y = drawing.height/2 YLabel.angle = 90 YLabel.textAnchor ='middle' YLabel.maxWidth = 100 YLabel.height = 20 YLabel._text = ylabel drawing.add(YLabel)
def setAxesLabels(self): xlabel = Label() xlabel.fontName = 'Helvetica' xlabel.fontSize = 12 xlabel.x = 450 xlabel.y = 40 xlabel._text = self._data_dict.get('xlabel', '') xlabel.maxWidth = 180 xlabel.height = 20 xlabel.textAnchor ='middle' self.add(xlabel, name='xlabel') ylabel = Label() ylabel.fontName = 'Helvetica' ylabel.fontSize = 12 ylabel.x = 20 ylabel.y = 210 ylabel.angle = 90 ylabel._text = self._data_dict.get('ylabel', '') ylabel.maxWidth = 180 ylabel.height = 20 ylabel.textAnchor ='middle' self.add(ylabel, name='ylabel')
def add_azure_findings_by_severity_chart(): drawing = Drawing(doc.width / 2 - 18, doc.height / 2 - 45) aws, azure = get_all_violations_by_severity() rules = [azure] maxVal = max(rules[0]) 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 = 10 bar.y = 70 bar.height = doc.height / 4 bar.width = doc.width / 2 - 40 bar.barWidth = 2 bar.barSpacing = 0.5 bar.data = rules bar.valueAxis.valueMin = 0 bar.valueAxis.valueMax = int( maxVal * 1.5) ## graph displa twice as much as max violation bar.valueAxis.valueStep = value_step ## Convert to neartest 10 bar.categoryAxis.categoryNames = ["high", "medium", "low"] bar.barLabelFormat = '%d' bar.barLabels.nudge = 15 bar.bars[0].fillColor = HexColor("#B170DB") bar.bars[0].strokeColor = None bar.categoryAxis.labels.boxAnchor = 'n' chartLabel = Label() chartLabel.setText("Findings by Severity - Azure") chartLabel.fontSize = 10 chartLabel.fontName = 'Helvetica-Bold' chartLabel.fillColor = HexColor("#737373") chartLabel.dx = doc.rightMargin chartLabel.dy = doc.height - 80 drawing.add(chartLabel) drawing.add(bar) fields.append(drawing)
def autoLegender( chart,title=''): width = 448 height = 230 d = Drawing(width,height) lab = Label() lab.x = 220 #x和y是文字的位置坐标 lab.y = 210 lab.setText(title) # lab.fontName = 'song' #增加对中文字体的支持 lab.fontSize = 20 d.add(lab) d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor="#868686",fillColor=None) #边框颜色 d.add(chart) return d
def addLabel(drawing, x, y, text, fontName='Helvetica', fontSize=11, dy=0, angle=0, boxAnchor='sw', textAnchor='start'): """Add a label to the drawing. This interface here is inconsistent in that it requires pixel coords. FIX This just sets convenient defaults for Label.""" label = Label() label.setText(text) label.setOrigin(x, y) label.fontName = fontName label.fontSize = fontSize label.boxAnchor = boxAnchor label.textAnchor = textAnchor label.dy = dy label.angle = angle drawing.add(label)
def addAxis(drawing, xmap, y, strokeWidth=1, minorStrokeWidth=0.5, tickDir='down', autoTicks=False, nTicks=20, tickLen=5, fontSize=10, nMinorTicks=80, minorTickLen=2, angle=0, dx=0, dy=-2, textAnchor='middle', boxAnchor=None, scale=1.0, format='%i'): """Add a horizontal axis to the drawing. To do: Round tick positions """ line = Line(xmap.x0, y, xmap.x1, y, strokeWidth=strokeWidth) drawing.add(line) if not boxAnchor: if tickDir=='down': boxAnchor = 'n' else: boxAnchor = 's' signum = {'up': -1, 'down': 1}[tickDir] if nTicks>0: ticks = tick_generator(xmap.start, xmap.end, n=nTicks, convert=int) for p in ticks: x = xmap(p) line = Line(x, y, x, y-signum*tickLen, strokeWidth=strokeWidth) drawing.add(line) s = Label() s.setOrigin(x, y-signum*tickLen) s.setText(format % (p/scale)) s.dx = dx s.dy = signum*dy s.fontName = 'Helvetica' s.fontSize = fontSize s.textAnchor = textAnchor s.boxAnchor = boxAnchor s.angle = angle drawing.add(s) minorticks = tick_generator(xmap.start, xmap.end, n=nMinorTicks, convert=int) for p in minorticks: x = xmap(p) line = Line(x, y, x, y-signum*minorTickLen, strokeWidth=minorStrokeWidth) drawing.add(line)
def radar(datos): tamanio = datos["tamanio"] data = datos["data"] labels = datos["labels"] colores = datos["colores"] titulo = datos["titulo"] grafico = SpiderChart() grafico.width = tamanio grafico.height = tamanio grafico.x = 0 grafico.y = 0 grafico.data = data grafico.labels = labels grafico.spokes.labelRadius = 1.125 grafico.spokes.strokeDashArray = (10,5) grafico.spokeLabels.fontSize = FONTSIZE grafico.spokeLabels.fontName = "Helvetica" grafico.strands[0].fillColor = colors.HexColor(colores[0]) grafico.strands[0].strokeColor = None grafico.strands[0].strokeWidth = 1 grafico.strands[1].fillColor = None grafico.strands[1].strokeColor = colors.HexColor(colores[1]) grafico.strands[1].strokeWidth = 2 grafico.strandLabels.format = 'values' grafico.strandLabels.fontSize = FONTSIZE-1 grafico.strandLabels.fontName = "Helvetica" grafico.strandLabels.fillColor = colors.black for i in range(len(datos["data"][0])): grafico.strandLabels[0,i]._text = "%2.2f" % data[0][i] grafico.strandLabels[0,i].dy = FONTSIZE grafico.strandLabels[1,i]._text = "%2.2f" % data[1][i] grafico.strandLabels[1,i].dy = -FONTSIZE retorno = crearDrawing(grafico) if titulo: etiqueta = Label() etiqueta.fontSize = FONTSIZE etiqueta.fontName = "Helvetica-Bold" etiqueta.setText(titulo) etiquetar(retorno, etiqueta, tamanio/2.0, 0.0) return retorno
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 torta(datos): tamanio = datos["tamanio"] data = datos["data"] labels = datos["labels"] colores = datos["colores"] titulo = datos["titulo"] grafico = Pie() grafico.x = 10 grafico.y = 10 grafico.startAngle = 45 grafico.width = tamanio grafico.height = tamanio grafico.data = data grafico.labels = labels grafico.slices.fontName = "Helvetica" grafico.slices.fontSize = FONTSIZE grafico.simpleLabels = False grafico.sideLabels = 1 grafico.sideLabelsOffset = 0.075 grafico.slices.label_simple_pointer = False grafico.slices.label_pointer_elbowLength = 0.5 grafico.slices.label_pointer_piePad = 3 grafico.slices.label_pointer_edgePad = 3 grafico.slices.label_pointer_strokeColor = colors.black grafico.slices.label_pointer_strokeWidth = 0.75 grafico.slices.strokeWidth=1.5 grafico.slices.strokeColor=colors.white for i in range(len(colores)): grafico.slices[i].fillColor = colors.HexColor(colores[i]) retorno = crearDrawing(grafico) if titulo: etiqueta = Label() etiqueta.fontSize = FONTSIZE etiqueta.fontName = "Helvetica-Bold" etiqueta.setText(titulo) etiquetar(retorno, etiqueta, tamanio/2.0, 0.0) return retorno
def border(): draw = Drawing(1, 1) rect = Polygon(points=[ -12, cm / 6, (PAGE_WIDTH - (RIGHT_MARGIN + LEFT_MARGIN)), cm / 6, PAGE_WIDTH - (RIGHT_MARGIN + LEFT_MARGIN), -1 * (PAGE_HEIGHT - (TOP_MARGIN + BOTTOM_MARGIN + cm / 2)), -12, -1 * (PAGE_HEIGHT - (TOP_MARGIN + BOTTOM_MARGIN + cm / 2)) ], strokeColor=Color(*charts.BG_COLOR)) rect.fillColor = Color(*charts.BG_COLOR, 0.1) draw.add(rect) draw.add(Circle(100, 90, 5, fillColor=colors.green)) lab = Label() lab.setOrigin(350, -50) lab.boxAnchor = 'ne' lab.fillColor = Color(*charts.BG_COLOR, 0.15) lab.fontSize = 72 lab.angle = 60 lab.dx = 0 lab.dy = 0 lab.setText('Wisdom Tests') draw.add(lab) return draw
def barras(datos): alto = datos["alto"] ancho = datos["ancho"] data = datos["data"] labels = datos["labels"] colores = datos["colores"] grafico = VerticalBarChart() grafico.x = 30 grafico.y = 0 grafico.height = alto grafico.width = ancho grafico.data = data grafico.barSpacing = 1.25 for i in range(len(colores)): color = colors.HexColor(colores[i]) grafico.bars[i].strokeColor = color grafico.bars[i].fillColor = color grafico.valueAxis.labels.fontName = "Helvetica" grafico.valueAxis.labels.fontSize = FONTSIZE grafico.valueAxis.valueMin = 0 grafico.valueAxis.valueMax = 100 grafico.valueAxis.valueStep = 10 grafico.categoryAxis.categoryNames = labels grafico.categoryAxis.labels.fontName = "Helvetica" grafico.categoryAxis.labels.fontSize = FONTSIZE grafico.categoryAxis.labels.dy = -FONTSIZE grafico.categoryAxis.labels.boxAnchor = 'c' grafico.categoryAxis.labels.angle = 0 retorno = crearDrawing(grafico) etiqueta = Label() etiqueta.setOrigin(0, alto) etiqueta.fontSize = FONTSIZE etiqueta.fontName = "Helvetica" etiqueta.setText("(%)") retorno.add(etiqueta) return retorno
def draw_line(self, line_data, *args, **kw): drawing = Drawing(400, 200) lp = LinePlot() lp.x = 30 lp.y = -20 lp.height = 200 lp.width = 400 lp.data = line_data lp.xValueAxis.labels.fontName = 'Helvetica' lp.xValueAxis.labels.fontSize = 7 lp.xValueAxis.forceZero = 0 lp.xValueAxis.avoidBoundFrac = 1 lp.xValueAxis.gridEnd = 115 lp.xValueAxis.tickDown = 3 lp.xValueAxis.labelTextFormat = lambda x: time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(int(x) / 1000)) lp.yValueAxis.tickLeft = 3 lp.yValueAxis.labels.fontName = 'Helvetica' lp.yValueAxis.labels.fontSize = 7 for i in range(len(line_data)): lp.lines[i].strokeColor = colors.toColor('hsl(%s,80%%,40%%)' % (i * 60)) drawing.add(lp) title = Label() title.fontName = 'Helvetica-Bold' title.fontSize = 14 title.x = 200 title.y = 180 title._text = 'Chart Title' title.maxWidth = 180 title.height = 20 title.textAnchor = 'middle' drawing.add(title) return drawing
def addAxis(drawing, xmap, y, fontSize=8, tickLen=4, minorTickLen=2, nTicks=20, strokeWidth=1, minorStrokeWidth=0.5): line = Line(xmap.x0, y, xmap.x1, y, strokeWidth=strokeWidth) drawing.add(line) ticks = tick_generator(xmap.start, xmap.end, n=nTicks, convert=int) for p in ticks: x = xmap(p) line = Line(x, y, x, y-tickLen, strokeWidth=strokeWidth) drawing.add(line) s = Label() s.setOrigin(x, y-tickLen) s.setText(str(p)) s.fontName = 'Helvetica' s.fontSize = fontSize s.textAnchor = 'middle' s.boxAnchor = 'n' drawing.add(s) minorticks = tick_generator(xmap.start, xmap.end, n=50, convert=int) for p in minorticks: x = xmap(p) line = Line(x, y, x, y-minorTickLen, strokeWidth=minorStrokeWidth) drawing.add(line)
def draw(self): g = Group() #box g.add(Rect(self.x,self.y,len(self.xlabels)*self.gridDivWidth,len(self.ylabels)*self.gridDivWidth, strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=None)) #internal gridding for f in range (1,len(self.ylabels)): #horizontal g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x, y1 = self.y+f*self.gridDivWidth, x2 = self.x+len(self.xlabels)*self.gridDivWidth, y2 = self.y+f*self.gridDivWidth)) for f in range (1,len(self.xlabels)): #vertical g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x+f*self.gridDivWidth, y1 = self.y, x2 = self.x+f*self.gridDivWidth, y2 = self.y+len(self.ylabels)*self.gridDivWidth)) # draw the 'dot' g.add(Circle(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=self.dotColor, cx = self.x+(self.dotXPosition*self.gridDivWidth), cy = self.y+(self.dotYPosition*self.gridDivWidth), r = self.dotDiameter/2.0)) #used for centering y-labels (below) ascent=getFont(self.labelFontName).face.ascent if ascent==0: ascent=0.718 # default (from helvetica) ascent=ascent*self.labelFontSize # normalize #do y-labels if self.ylabels != None: for f in range (len(self.ylabels)-1,-1,-1): if self.ylabels[f]!= None: g.add(String(strokeColor=self.gridColor, text = self.ylabels[f], fontName = self.labelFontName, fontSize = self.labelFontSize, fillColor=_PCMYK_black, x = self.x-self.labelOffset, y = self.y+(f*self.gridDivWidth+(self.gridDivWidth-ascent)/2.0), textAnchor = 'end')) #do x-labels if self.xlabels != None: for f in range (0,len(self.xlabels)): if self.xlabels[f]!= None: l=Label() l.x=self.x+(f*self.gridDivWidth)+(self.gridDivWidth+ascent)/2.0 l.y=self.y+(len(self.ylabels)*self.gridDivWidth)+self.labelOffset l.angle=90 l.textAnchor='start' l.fontName = self.labelFontName l.fontSize = self.labelFontSize l.fillColor = _PCMYK_black l.setText(self.xlabels[f]) l.boxAnchor = 'sw' l.draw() g.add(l) return g
def exportMonthlyReport(self, file, month, year): """Outputs the monthly report to the specified file location Parameters: self: the class instance file: str - file location and name ending in .pdf month: str - required month year: int - required year """ # For conversion of month to three letter abbreviation months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] # Creating a title title = Label() title.setOrigin(300, 20) title.boxAnchor = 'ne' title.dx = 0 title.dy = -5 title.fontSize = 30 title.setText("Monthly Report") # Adding title to a drawing draw_title = Drawing(0, 40) draw_title.add(title) # Creating a subtitle subtitle = Label() subtitle.setOrigin(320, 20) subtitle.boxAnchor = 'ne' subtitle.dx = 0 subtitle.dy = -10 subtitle.fontSize = 14 # Converts month to three letter abbreviation str_month = months[int(month) - 1] # Setting the subtitle's text subtitle.setText("Australia Zoo Wildlife Hospital, " + str_month + " " + str(year)) # Adding subtitle to a drawing draw_subtitle = Drawing(0, 30) draw_subtitle.add(subtitle) # Creating a label for the first chart label_lga = Label() label_lga.setOrigin(180, 20) label_lga.boxAnchor = 'ne' label_lga.dx = 0 label_lga.dy = -20 label_lga.setText("Local Government Area Totals") # Adding label to a drawing draw_label_lga = Drawing(0, 40) draw_label_lga.add(label_lga) # Creating drawing for the lga chart draw_lga = Drawing(0, 270) draw_lga.add(self.getSpecificBarChart("LGA", month, year)) # Creating a label for the second chart label_taxons = Label() label_taxons.setOrigin(180, 20) label_taxons.boxAnchor = 'ne' label_taxons.dx = 0 label_taxons.dy = -20 label_taxons.setText("Taxon Grouping Totals") # Adding label to a drawing draw_label_taxons = Drawing(0, 40) draw_label_taxons.add(label_taxons) # Creating drawing for the taxons chart draw_taxons = Drawing(0, 270) draw_taxons.add(self.getSpecificBarChart("Taxons", month, year)) # List of drawings in order of how to place them in the canvas drawlist = [ draw_title, draw_subtitle, draw_label_lga, draw_lga, draw_label_taxons, draw_taxons ] # Creating a canvas (pdf file) and saving it to a location canvas = Canvas(file) # Creating a frame to add flowables (drawings) to frame = Frame(inch, 0, 15.92 * cm, 29.7 * cm) # Adding flowables frame.addFromList(drawlist, canvas) # Saving the pdf canvas.save()
def _rawDraw(self, x, y): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS from reportlab.graphics.charts.axes import XCategoryAxis,YValueAxis from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.charts.barcharts import VerticalBarChart self.originX = x self.originY = y self._setScale([self.dataBar]) (x1, y1, Width, Height) = self._getGraphRegion(x, y) #Build the graph self.drawing = Drawing(self.width, self.height) #Size of the Axis SizeXaxis = 14 countSteps = int(self.valueMax / self.valueStep) SizeYaxis = 0.0 for n in range(countSteps + 1): eachValue = self.valueMin + n * self.valueStep textString = self._customSecondsLabelFormat( eachValue ) SizeYaxis = max(SizeYaxis, self._stringWidth(textString, STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) ) bc = VerticalBarChart() SizeYaxis += bc.valueAxis.tickLeft bc.x = x1 - x + SizeYaxis bc.y = y1 - y + SizeXaxis bc.height = Height - SizeXaxis bc.width = Width - SizeYaxis self.graphCenterX = bc.x + bc.width/2 self.graphCenterY = bc.y + bc.height/2 if self.validData: # add valid data to chart bc.data = self.dataBar bc.categoryAxis.categoryNames = self.dataNames # axis values bc.valueAxis.valueMin = self.valueMin bc.valueAxis.valueMax = self.valueMax bc.valueAxis.valueStep = self.valueStep # add value labels above bars bc.barLabelFormat = self._customSecondsLabelFormat bc.barLabels.dy = 0.08*inch bc.barLabels.fontSize = 6 else: # no valid data bc.data = [ (0, ), ] bc.categoryAxis.categoryNames = [ '' ] bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 1 bc.valueAxis.valueStep = 1 Nodata = Label() Nodata.fontSize = 12 Nodata.angle = 0 Nodata.boxAnchor = 'c' Nodata.dx = self.graphCenterX Nodata.dy = self.graphCenterY Nodata.setText("NO VALID DATA") self.drawing.add(Nodata) # chart formatting (R,G,B) = VeriwaveYellow bc.bars[0].fillColor = colors.Color(R,G,B) bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat # axis labels bc.categoryAxis.labels.boxAnchor = 'c' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.labels.fontSize = 8 # add chart self.drawing.add(bc) #Adjust the labels to be the center of the graph self._drawLabels(self.title, "", "") # Add Legend in upper right corner legendHeight = 9 legendX = bc.x + 5 legendY = bc.y + bc.height - 12 self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[0].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'MIN', fontName='Helvetica', fontSize=8)) legendY -= legendHeight self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[1].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'MAX', fontName='Helvetica', fontSize=8)) legendY -= legendHeight self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[2].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'AVG', fontName='Helvetica', fontSize=8)) legendY -= legendHeight
legend.dxTextSpace = 5 legend.dy = 5 legend.dx = 5 legend.deltay = 5 legend.alignment ='right' drawing.add(lp) drawing.add(legend) if title != None: label = Label() label.x = w label.y = h - 25 label.boxAnchor = 'se' label.fontName = 'Helvetica' label.fontSize = 10 label.setText(title) drawing.add(label) return drawing def drawTable(self, data): t = Table(data, None, None, None, 1, 1, 1) extraStyle = [] for i in range(len(data[1:])): if data[1:][i][0] == 'Free' or data[1:][i][0] == 'Used': extraStyle.append(('BACKGROUND', (0, i + 1), (-1, i + 1), colors.orange)) if data[1:][i][0] == 'SwapUsage' or data[1:][i][0] == 'LMK File': extraStyle.append(('BACKGROUND', (0, i + 1), (-1, i + 1), colors.lightgreen)) t.setStyle(TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica'), ('BACKGROUND', (0, 0), (-1, 0), colors.deepskyblue), ('FONTSIZE', (0, 0), (-1, -1), 10),
lp.lines.symbol = makeMarker('FilledCircle') lp.xValueAxis.valueMin = 1 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 500 lp.yValueAxis.valueStep = 100 drawing.add(lp) title = Label() #若需要显示中文,需要先注册一个中文字体 pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc")) title.fontName = "haha" title.fontSize = 12 title_text = '你好' #title_text = "abc" title._text = title_text title.x = 250 title.y = 280 title.textAnchor = 'middle' drawing.add(title) Xlabel = Label() Xlabel._text = 'x' Xlabel.fontSize = 12 Xlabel.x = 480 Xlabel.y = 30 Xlabel.textAnchor = 'middle' drawing.add(Xlabel)
def draw(self): g = Group() #box g.add( Rect(self.x, self.y, len(self.xlabels) * self.gridDivWidth, len(self.ylabels) * self.gridDivWidth, strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=None)) #internal gridding for f in range(1, len(self.ylabels)): #horizontal g.add( Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1=self.x, y1=self.y + f * self.gridDivWidth, x2=self.x + len(self.xlabels) * self.gridDivWidth, y2=self.y + f * self.gridDivWidth)) for f in range(1, len(self.xlabels)): #vertical g.add( Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1=self.x + f * self.gridDivWidth, y1=self.y, x2=self.x + f * self.gridDivWidth, y2=self.y + len(self.ylabels) * self.gridDivWidth)) # draw the 'dot' g.add( Circle(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=self.dotColor, cx=self.x + (self.dotXPosition * self.gridDivWidth), cy=self.y + (self.dotYPosition * self.gridDivWidth), r=self.dotDiameter / 2.0)) #used for centering y-labels (below) ascent = getFont(self.labelFontName).face.ascent if ascent == 0: ascent = 0.718 # default (from helvetica) ascent = ascent * self.labelFontSize # normalize #do y-labels if self.ylabels != None: for f in range(len(self.ylabels) - 1, -1, -1): if self.ylabels[f] != None: g.add( String(strokeColor=self.gridColor, text=self.ylabels[f], fontName=self.labelFontName, fontSize=self.labelFontSize, fillColor=_PCMYK_black, x=self.x - self.labelOffset, y=self.y + (f * self.gridDivWidth + (self.gridDivWidth - ascent) / 2.0), textAnchor='end')) #do x-labels if self.xlabels != None: for f in range(0, len(self.xlabels)): if self.xlabels[f] != None: l = Label() l.x = self.x + (f * self.gridDivWidth ) + (self.gridDivWidth + ascent) / 2.0 l.y = self.y + (len(self.ylabels) * self.gridDivWidth) + self.labelOffset l.angle = 90 l.textAnchor = 'start' l.fontName = self.labelFontName l.fontSize = self.labelFontSize l.fillColor = _PCMYK_black l.setText(self.xlabels[f]) l.boxAnchor = 'sw' l.draw() g.add(l) return g