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 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 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 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 _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 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 comparison_graphs(comparison_values, location, emission, default_emissions, default_location): s = Spacer(9 * inch, .2 * inch) Elements.append(s) drawing = Drawing(0, 0) if not default_location: bc = gen_bar_graphs(comparison_values, location, emission) bc.y = -120 bc.height = 125 bc.width = 300 drawing.add(bc) else: bc1 = gen_bar_graphs(default_emissions[:3], location, emission) bc2 = gen_bar_graphs(default_emissions[3:6], location, emission) bc3 = gen_bar_graphs(default_emissions[6:], location, emission) offset = -257 bc1.x = -10 + offset bc2.x = 190 + offset bc3.x = 390 + offset drawing.add(bc1) drawing.add(bc2) drawing.add(bc3) label_offset = offset + 80 label1, label2, label3 = Label(), Label(), Label() label1.setText("Global (excluding Europe and US)") label1.x, label1.y = -17 + label_offset, -160 label1.fontName = "Times-Bold" label2.setText("Europe") label2.x, label2.y = 185 + label_offset, -160 label2.fontName = "Times-Bold" label3.setText("United States") label3.x, label3.y = 385 + label_offset, -160 label3.fontName = "Times-Bold" drawing.add(label1) drawing.add(label2) drawing.add(label3) if_elsewhere_para = Paragraph( '<font face="times" size=12>Kilograms of CO<sub rise = -10 size' + ' = 8>2 </sub> emissions for the function if the computation had been performed elsewhere</font>', style=styles["Normal"]) graph_data = [['Emission Comparison'], [if_elsewhere_para], [drawing]] graph_table = Table(graph_data, [6.5 * inch], [.25 * inch, .25 * inch, .25 * inch], hAlign="CENTER") graph_table.setStyle( TableStyle([('FONT', (0, 0), (0, 0), "Times-Bold"), ('FONT', (0, 1), (0, 1), "Times-Roman"), ('FONTSIZE', (0, 0), (0, 0), 13), ('FONTSIZE', (0, 1), (0, 1), 12), ('ALIGN', (0, 0), (-1, -1), "CENTER")])) Elements.append(graph_table)
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 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 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 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 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 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 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 d = Drawing(width, height) lab = Label() lab.x = 220 #x和y是文字的位置坐标 lab.y = 210 lab.setText(title) lab.fontName = 'msyh' #增加对中文字体的支持 lab.fontSize = 20 d.add(lab) d.background = Rect(0, 0, width, height, strokeWidth=1.5, strokeColor="#000000", fillColor=None) #边框颜色 d.add(chart) 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 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 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 half_year(title,city, year, startmon): '''startmon is the 1-indexed month to start the page on''' reqd, mons = get_months(year, startmon) LEFTMARGIN = 5 DAYCOLWIDTH = 50 CELLWIDTH = 80 CELLHEIGHT = 19 TOPROWHEIGHT = 18 WIDTH = LEFTMARGIN + DAYCOLWIDTH + CELLWIDTH*6 HEIGHT = reqd * CELLHEIGHT + TOPROWHEIGHT d = shapes.Drawing(WIDTH, HEIGHT) lab = Label() lab.setOrigin(LEFTMARGIN,HEIGHT) lab.boxAnchor = 'nw' lab.setText(title) lab.fontName = 'Times-Bold' d.add(lab) # Month headings for i in range(6): x = LEFTMARGIN + i*CELLWIDTH + DAYCOLWIDTH + CELLWIDTH/2 month_name = calendar.month_abbr[i + startmon] d.add(shapes.String(x, HEIGHT-14, month_name, fontSize=14, fontName='Times-Bold', textAnchor='middle')) # Day row headings for i in range(reqd): y = HEIGHT - i*CELLHEIGHT - TOPROWHEIGHT weekday_name = calendar.day_abbr[i%7] d.add(shapes.String(LEFTMARGIN + 10, y-14, weekday_name, fontSize=14)) # Draw the day cells, for each month for j in range(6): x = LEFTMARGIN + j*CELLWIDTH + DAYCOLWIDTH # for each day for i in range(reqd): if i >= len(mons[j]) or not mons[j][i]: continue y = HEIGHT - i*CELLHEIGHT - TOPROWHEIGHT # cells for each day, light grey background if weekend weekend = i%7 > 4 lightgrey = colors.HexColor(0xD0B090) color = weekend and lightgrey or colors.white # Now we have (x, y, color) for (year, month=j+startmon, day=mons[j][i]) # Get the ephemerides for the date date = datetime.datetime(year, j+startmon, mons[j][i]) (sunrise, sunset, moon_phase, moon_fm) = ephem3.ephem_one_day(city, date) # Insert the date cell at x, y d.add(shapes.Rect(x, y, CELLWIDTH, -CELLHEIGHT, fillColor=color)) d.add(shapes.String(x+1, y-10, str(mons[j][i]), fontSize=10)) green = colors.HexColor(0x207020) # Insert the moon phase if moon_fm: d.add(shapes.String(x+15, y-10, moon_fm, fontSize=8, fillColor=green)) # for each day # for each month return d
legend.fontSize = 8 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),
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 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 get_pdf_results(task_id): # Flask response response = Response() response.status_code = 200 task = data.get_task_result(task_id) #Saving file to a in-memory file output_file = StringIO.StringIO() def header_footer(canvas, doc): canvas.saveState() background = 'static/img/pdf_bg.png' canvas.drawImage(background, 1 * inch, 5.75 * inch, width=8 * inch, height=6 * inch, mask='auto') # Header logo = Image('static/img/logo/logo.png') logo.drawHeight = 0.5 * inch logo.drawWidth = 1.75 * inch date = datetime.now().strftime("%y-%m-%d %H:%M") headerData = [[logo, '', date]] headerTable = Table(headerData, colWidths=[2 * inch, 3.58 * inch, 1.2 * inch], style=[('LINEBELOW', (0, 0), (2, 0), 1, colors.HexColor(0xcccccc)), ('TEXTCOLOR', (0, 0), (2, 0), colors.HexColor(0x807F83)), ('VALIGN', (1, 0), (1, 0), 'MIDDLE'), ('VALIGN', (2, 0), (2, 0), 'MIDDLE')]) headerTable.wrapOn(canvas, doc.width, doc.topMargin) headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin) pageNum = "Page %d" % doc.page footerData = [[ 'KAPSARC Building Energy Assessment Tool (BEAT)', pageNum ]] footerTable = Table(footerData, colWidths=[5.76 * inch, 1 * inch], style=[('LINEABOVE', (0, 0), (1, 0), 2, colors.HexColor(0xcccccc)), ('TEXTCOLOR', (0, 0), (1, 0), colors.HexColor(0x807F83)), ('ALIGN', (1, 0), (1, 0), 'RIGHT')]) footerTable.wrapOn(canvas, doc.width, doc.bottomMargin) footerTable.drawOn(canvas, doc.leftMargin, 0.5 * inch) canvas.restoreState() pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) styles = getSampleStyleSheet() # Title styles.add( ParagraphStyle(name='styleTitle', alignment=TA_CENTER, fontSize=16, fontName='Vera', textColor=colors.HexColor(0x61a659), leading=30, spaceBefore=35, spaceAfter=10)) # Headings styles.add( ParagraphStyle(name='styleHeading', parent=styles['Heading2'], fontSize=14, textColor=colors.HexColor(0x807F83), leading=20, spaceBefore=10, underlineProportion=1.1, spaceAfter=10)) styles.add( ParagraphStyle(name='styleHeading2', parent=styles['Heading2'], fontSize=14, textColor=colors.HexColor(0x61a659), leading=20, spaceBefore=20, underlineProportion=1.1, spaceAfter=20)) styles.add( ParagraphStyle( name='styleHeading3', #alignment= TA_CENTER, fontSize=12, fontName='Vera', textColor=colors.HexColor(0x61a659), leading=20, spaceBefore=10, spaceAfter=5)) # Body text styles.add( ParagraphStyle(name='styleBodyText', parent=styles['Normal'], fontSize=9, textColor=colors.HexColor(0x666666), spaceBefore=5, spaceAfter=15)) styleTitle = styles['styleTitle'] styleHeading = styles['styleHeading'] styleHeading2 = styles['styleHeading2'] styleHeading3 = styles['styleHeading3'] styleBodyText = styles['styleBodyText'] pdf_chart_colors = [ "#3D6531", "#61a24f", "#89B97B", "#B0D1A7", "#cde5c7", "#7e7f82", "#9E9FA1", "#BFBFC1", "#DFDFE0", "#ffd200", "#FFE360", "#FFEE9F", ] Elements = [] doc = BaseDocTemplate(output_file, showBoundary=0, pagesize=A4, title='KASPSARC BEAT Report', author="KAPSARC", leftMargin=0.75 * inch, rightMargin=0.75 * inch, topMargin=inch, bottomMargin=inch) frame = Frame(doc.leftMargin, doc.topMargin, doc.width, doc.height, topPadding=0.3 * inch, showBoundary=0) template = PageTemplate(id='template', frames=[frame], onPage=header_footer) doc.addPageTemplates([template]) ## PAGE 1 #add some flowables Elements.append( Paragraph("KAPSARC Building Energy Assessment Tool (BEAT)", styleTitle)) Elements.append(Paragraph("Your Building Description", styleHeading)) rowHeights = 0.3 * inch calibrationData = task['calibrationData'] Elements.append(Paragraph("General Information:", styleHeading3)) infoTableData = [ [ Paragraph('<b>- Name: </b>' + calibrationData['txtBldgName'], styleBodyText), Paragraph('<b>- Address: </b>' + calibrationData['txtBldgAddress'], styleBodyText), Paragraph('<b>- Type: </b>' + calibrationData['cmbBldgType'], styleBodyText) ], [ Paragraph( '<b>- Location: </b>' + calibrationData['cmbBldgLocation'], styleBodyText), Paragraph('<b>- Shape: </b>' + calibrationData['cmbBldgShape'], styleBodyText), Paragraph( '<b>- Floor Area (m' + u"\u00b2" + '): </b>' + str(calibrationData['txtFloorArea']), styleBodyText) ] ] infoTable = Table(infoTableData, colWidths=[160, 165, 150], rowHeights=rowHeights) Elements.append(infoTable) Elements.append(Paragraph('<br />', styleBodyText)) Elements.append(Paragraph("Envelope Construction Details:", styleHeading3)) envTableData = [ [ Paragraph( '<b>- South Wall: </b>' + calibrationData['cmbSouthWall'], styleBodyText), Paragraph('<b>- West Wall: </b>' + calibrationData['cmbWestWall'], styleBodyText) ], [ Paragraph( '<b>- North Wall: </b>' + calibrationData['cmbNorthWall'], styleBodyText), Paragraph('<b>- East Wall: </b>' + calibrationData['cmbEastWall'], styleBodyText) ], [ Paragraph('<b>- Roof: </b>' + calibrationData['cmbRoof'], styleBodyText), Paragraph( '<b>- Floor: </b>' + calibrationData['cmbFirstFloorContact'], styleBodyText) ], [ Paragraph('<b>- Windows Type: </b>' + calibrationData['glasstype'], styleBodyText), Paragraph( '<b>- Overhang Depth (m): </b>' + str(calibrationData['txtWinSouthOverhang']), styleBodyText) ] ] envTable = Table(envTableData, colWidths=[240, 235], rowHeights=rowHeights) Elements.append(envTable) Elements.append(Paragraph('<br />', styleBodyText)) Elements.append(Paragraph("Air Conditioning Systems", styleHeading3)) hvacTableData = [[ Paragraph( '<b>- HVAC System Type: </b>' + calibrationData['cmbBldgSystem'], styleBodyText), Paragraph( '<b>- Cooling Temperature Setting (' + u"\u00b0" + 'C): </b>' + str(calibrationData['txtCoolSetTemp']), styleBodyText) ], [ Paragraph( '<b>- Energy Efficiency Ratio (EER): </b>' + str(calibrationData['eir']), styleBodyText), Paragraph( '<b>- Heating Temperature Setting (' + u"\u00b0" + 'C): </b>' + str(calibrationData['txtHeatSetTemp']), styleBodyText) ]] hvacTable = Table(hvacTableData, colWidths=[240, 235], rowHeights=rowHeights) Elements.append(hvacTable) Elements.append(Paragraph('<br />', styleBodyText)) Elements.append(Paragraph("Overall Assessment", styleHeading)) Elements.append( Paragraph( "Based on your description and current SASO requirements, the tool provides the following assessments:", styleBodyText)) if task['compliant']: compliant = "<strong><font color=green>meets</font></strong>" else: compliant = "<strong><font color=red>does not meet</font></strong>" if (task['ngEnergyDiff'] < 0): energyDiff = "<strong><font color=green>" + str( task['energyDiff']) + " kWh/year, less</font></strong>" else: energyDiff = "<strong><font color=red>" + str( task['energyDiff']) + " kWh/year, more</font></strong>" Elements.append( Paragraph( "- Your building " + compliant + " SASO requirements for all building envelope", styleBodyText)) Elements.append( Paragraph( "- Your building consumed " + energyDiff + " than the SASO Baseline", styleBodyText)) if task['compliant']: Elements.append( Paragraph( "- You may reduce even more your energy consumption in your building by using LED lamps and high efficient appliances and air conditioning system", styleBodyText)) else: Elements.append( Paragraph( " - You need to add more insulation to the walls and/or roof, or use more efficient window glazing to comply with SASO requirements", styleBodyText)) if not task['compliant'] and (task['ngEnergyDiff'] >= 0): Elements.append( Paragraph( " - You may also consider using LED lamps and energy efficient appliances and air conditioning system", styleBodyText)) Elements.append(PageBreak()) Elements.append( Paragraph("How electricity is used in your building?", styleHeading3)) Elements.append( Paragraph( "Your building needs electricity to operate several types of equipment including: air-conditioning, lighting, appliances and domestic hot water.", styleBodyText)) #add image Elements.append( Image('static/img/results-intro.png', width=4 * inch, height=1.2 * inch)) #add text Elements.append( Paragraph( "Based on the description you provided as well as typical lighting and appliances used in households, here how your building consumes electricity on annual basis:", styleBodyText)) bepuPieData = task['bepuPieData'] bepuTableData = [[0 for i in xrange(len(bepuPieData[0]))] for i in xrange(len(bepuPieData) + 1)] bepuChartLabel = [0 for i in xrange(len(bepuPieData))] bepuChartData = [0 for i in xrange(len(bepuPieData))] bepuTableData[0][0] = 'End-Use' bepuTableData[0][1] = 'Annual Electricity Use' for i, result in enumerate(bepuPieData): # write body cells bepuTableData[i + 1][0] = str(result['label']) bepuTableData[i + 1][1] = int(result['value']) bepuChartLabel[i] = str(result['label']) bepuChartData[i] = result['value'] #add chart bepuChart = Drawing(400, 200) pc = Pie() pc.data = bepuChartData labelc = [0 for i in xrange(len(bepuChartData))] for i, r in enumerate(bepuChartData): labelc[i] = str(round(r / sum(bepuChartData) * 100, 1)) + "%" pc.labels = labelc pc._seriesCount = len(bepuChartLabel) pc.slices.strokeColor = colors.HexColor(0xffffff) pc.slices.strokeWidth = 0.5 bepu_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0', '#98cd99'] for i, r in enumerate(bepuChartLabel): pc.slices[i].fillColor = colors.HexColor(bepu_chart_colors[i]) pc.width = pc.height = 120 pc.x = 40 pc.y = 30 # add_legend(d, pc) legend = Legend() legend.alignment = 'right' legend.x = pc.width + pc.x + 80 legend.y = pc.height - 10 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = 8 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 10 legend.autoXPadding = 10 legend.yGap = 0 legend.dxTextSpace = 5 legend.dividerLines = 1 | 2 | 4 legend.dividerOffsY = 6 legend.subCols.rpad = 70 legend.dividerColor = colors.HexColor(0xdedede) legend.colorNamePairs = [(pc.slices[i].fillColor, (bepuChartLabel[i][0:20], ' %s ' % "{:,}".format(int(pc.data[i])))) for i in xrange(len(pc.data))] legendHeader = Legend() legendHeader.colorNamePairs = [ ('', ('End-Use', 'Annual Electricity Use\n(kWh/year)')) ] legendHeader.alignment = 'right' legendHeader.x = legend.x - 20 legendHeader.y = legend.y + 30 legendHeader.fontName = 'Helvetica' legendHeader.fillColor = colors.HexColor(0x807F83) legendHeader.fontSize = 10 legendHeader.boxAnchor = 'nw' legendHeader.subCols.rpad = 80 legendFooter = Legend() legendFooter.colorNamePairs = [ ('', ('Total', str("{:,}".format(int(sum(bepuChartData)))) + '')) ] legendFooter.alignment = 'right' legendFooter.x = legendHeader.x + 5 legendFooter.y = legend.y - (len(bepuChartLabel) + 1) * 10 legendFooter.fontName = 'Helvetica-Bold' legendFooter.fillColor = colors.HexColor(0x807F83) legendFooter.fontSize = 10 legendFooter.boxAnchor = 'nw' legendFooter.subCols.rpad = 145 bepuChart.add(legend) bepuChart.add(legendHeader) bepuChart.add(legendFooter) pc.slices.fontColor = colors.HexColor(0x807F83) n = len(pc.data) bepuChart.add(pc, '') Elements.append(bepuChart) ## PAGE 2 Elements.append( Paragraph("When electricity is consumed in your building?", styleHeading3)) Elements.append( Paragraph( "Based on the weather of your location as well as typical lighting and appliances used in households, your building consumes electricity as noted in the following monthly profile:", styleBodyText)) #add chart pseBarData = task['pseBarData'] pseTableData = [[0 for i in xrange(len(pseBarData[0]['values']) + 1)] for i in xrange(len(pseBarData) + 1)] pseChartData = [[0 for i in xrange(len(pseBarData[0]['values']))] for i in xrange(len(pseBarData))] pseChartLegend = [0 for i in xrange(len(pseBarData))] pseTableData[0][0] = 'Key' month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] for i, m in enumerate(month): pseTableData[0][i + 1] = str(month[i]) for i, result in enumerate(pseBarData): # write body cells pseTableData[i + 1][0] = str(result['key']) pseChartLegend[i] = str(result['key']) for j, value in enumerate(result['values']): pseTableData[i + 1][j + 1] = int(result['values'][j]['y']) pseChartData[i][j] = int(result['values'][j]['y']) pseChart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 70 bc.y = 0 bc.height = 200 bc.width = 300 bc.data = pseChartData bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.strokeWidth = 0 bc.valueAxis.valueMin = 0 bc.categoryAxis.style = 'stacked' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 10 bc.categoryAxis.labels.dy = -2 bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.strokeWidth = 0.5 bc.valueAxis.strokeColor = colors.HexColor(0x807F83) bc.categoryAxis.strokeWidth = 0.5 bc.categoryAxis.strokeColor = colors.HexColor(0x807F83) bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 10 bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.categoryNames = month # create a list and add the elements of our document (image, paragraphs, table, chart) to it #add our barchart and legend bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.bars.strokeColor = colors.HexColor(0xffffff) bc.bars.strokeWidth = 0. pse_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0'] for i, r in enumerate(pseChartLegend): bc.bars[i].fillColor = colors.HexColor(pse_chart_colors[i]) # = colors.blue legend = Legend() legend.alignment = 'right' legend.x = bc.width + bc.x + 5 legend.y = bc.height + bc.y legend.deltax = 40 legend.dxTextSpace = 5 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = (len(bc.data) + 1) / 2 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 12 legend.dividerColor = colors.HexColor(0xdedede) legend.columnMaximum = len(pseChartLegend) legend.colorNamePairs = [(bc.bars[i].fillColor, pseChartLegend[i]) for i in xrange(len(bc.data))] #pseChart.hAlign = 'RIGHT' label = Label() label.setOrigin(10, bc.height / 2) #label.boxAnchor = 'sw' label.angle = 90 label.fillColor = colors.HexColor(0x807F83) label.setText('Electricity Consumption (kWh)') label.fontName = 'Helvetica' pseChart.add(legend, 'legend') pseChart.add(bc) pseChart.add(label) Elements.append(pseChart) Elements.append(PageBreak()) ## PAGE 3 Elements.append( Paragraph( "Does your building meet SASO Thermal Performance Requirements?", styleHeading3)) Elements.append( Paragraph( "Based on your description, the thermal transmittance properties of the walls, roof and glazing are calculated, and compared with SASO thermal building performance requirements:", styleBodyText)) #add chart lvdData = task['lvdData'] lvdChartData = [[0 for i in xrange(len(lvdData[0]['values']))] for i in xrange(len(lvdData))] lvdChartCategoryNames = [0 for i in xrange(len(lvdData[0]['values']))] lvdComparedObjKey = [0 for i in xrange(len(lvdData))] for i, result in enumerate(lvdData): # write body cells lvdComparedObjKey[i] = str(lvdData[i]['key']) for j, value in enumerate(result['values']): lvdChartCategoryNames[j] = value['label'] lvdChartData[i][j] = value['value'] lvdChart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 70 bc.y = 0 bc.height = 200 bc.width = 300 bc.data = lvdChartData bc.strokeColor = colors.black # bc.fillColor=colors.blue bc.valueAxis.valueMin = 0 bc.strokeWidth = 0 bc.valueAxis.valueMin = 0 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 20 bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.strokeWidth = 0.5 bc.valueAxis.strokeColor = colors.HexColor(0x807F83) bc.categoryAxis.strokeWidth = 0.5 bc.categoryAxis.strokeColor = colors.HexColor(0x807F83) bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 8 bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.categoryNames = lvdChartCategoryNames bc.categoryAxis.labels.angle = 0 # create a list and add the elements of our document (image, paragraphs, table, chart) to it #add our barchart and legend bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.bars.strokeColor = colors.HexColor(0xffffff) bc.bars.strokeWidth = 0.5 lvd_chart_colors = ['#5894D0', '#F67A40'] for i, r in enumerate(lvdComparedObjKey): bc.bars[i].fillColor = colors.HexColor(lvd_chart_colors[i]) # = colors.blue legend = Legend() legend.alignment = 'right' legend.x = bc.width + bc.x + 5 legend.y = bc.height + bc.y legend.deltax = 40 legend.dxTextSpace = 5 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = (len(bc.data) + 1) / 2 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 12 legend.dividerColor = colors.HexColor(0xdedede) legend.columnMaximum = len(lvdComparedObjKey) legend.colorNamePairs = [(bc.bars[i].fillColor, lvdComparedObjKey[i]) for i in xrange(len(bc.data))] #pseChart.hAlign = 'RIGHT' label = Label() label.setOrigin(10, bc.height / 2) #label.boxAnchor = 'sw' label.angle = 90 label.fillColor = colors.HexColor(0x807F83) label.setText('Envelope U-value (W/m' + u'\u00b2' + '.k)') label.fontName = 'Helvetica' lvdChart.add(label) lvdChart.add(legend, 'legend') lvdChart.add(bc) Elements.append(lvdChart) #Elements.append(PageBreak()) Elements.append(Paragraph('<br /><br />', styleBodyText)) ## PAGE 4 Elements.append( Paragraph("How energy efficient is your building?", styleHeading3)) Elements.append( Paragraph( "Using your input specifications, the annual electricity consumption is calculated and compared with a similar building that meets SASO requirements:", styleBodyText)) #add chart bepuComparisonData = task['bepuComparisonData'] bepuComparisonChartData = [[ 0 for i in xrange(len(bepuComparisonData[0]['values'])) ] for i in xrange(len(bepuComparisonData))] bepuChartCategoryNames = [ 0 for i in xrange(len(bepuComparisonData[0]['values'])) ] bepuComparedObjKey = [0 for i in xrange(len(bepuComparisonData))] for i, result in enumerate(bepuComparisonData): # write body cells bepuComparedObjKey[i] = str(bepuComparisonData[i]['key']) for j, value in enumerate(result['values']): bepuChartCategoryNames[j] = value['label'] bepuComparisonChartData[i][j] = value['value'] bepuComparisonChart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 70 bc.y = 0 bc.height = 200 bc.width = 300 bc.data = bepuComparisonChartData bc.strokeColor = colors.black # bc.fillColor=colors.blue bc.valueAxis.valueMin = 0 bc.strokeWidth = 0 bc.valueAxis.valueMin = 0 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 10 bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 20 bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.strokeWidth = 0.5 bc.valueAxis.strokeColor = colors.HexColor(0x807F83) bc.categoryAxis.strokeWidth = 0.5 bc.categoryAxis.strokeColor = colors.HexColor(0x807F83) bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 10 bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.categoryNames = bepuChartCategoryNames bc.categoryAxis.labels.angle = 30 # create a list and add the elements of our document (image, paragraphs, table, chart) to it #add our barchart and legend bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.bars.strokeColor = colors.HexColor(0xffffff) bc.bars.strokeWidth = 0.5 bepu_chart_colors = ['#5894D0', '#F67A40'] for i, r in enumerate(bepuComparedObjKey): bc.bars[i].fillColor = colors.HexColor(bepu_chart_colors[i]) # = colors.blue # bc.bars[1].fillColor = colors.lightblue legend = Legend() legend.alignment = 'right' legend.x = bc.width + bc.x + 5 legend.y = bc.height + bc.y legend.deltax = 40 legend.dxTextSpace = 5 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = (len(bc.data) + 1) / 2 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 12 legend.dividerColor = colors.HexColor(0xdedede) legend.columnMaximum = len(bepuComparedObjKey) legend.colorNamePairs = [(bc.bars[i].fillColor, bepuComparedObjKey[i]) for i in xrange(len(bc.data))] #pseChart.hAlign = 'RIGHT' label = Label() label.setOrigin(10, bc.height / 2) #label.boxAnchor = 'sw' label.angle = 90 label.fillColor = colors.HexColor(0x807F83) label.setText('Annual Energy Use (kWh/year)') label.fontName = 'Helvetica' bepuComparisonChart.add(label) bepuComparisonChart.add(legend, 'legend') bepuComparisonChart.add(bc) Elements.append(bepuComparisonChart) Elements.append(PageBreak()) doc.build(Elements) output_file.seek(0) # Set filname and mimetype file_name = 'K-BEAT_export_{}.pdf'.format( datetime.now().strftime("%Y-%m-%d %H:%M:%S")) #Returning the file from memory return send_file(output_file, attachment_filename=file_name, as_attachment=True)
def draw_hex(self): print 'Reporting Hex' story = [] for p in self.world.packets: pl,t = p.build_ps() XSTART = 0 XDSTART = 210 y = 0.0 XMUL= 100.0 YMUL = 10.0 larg = 16 YDUMP = PAGE_HEIGHT*0.80/YMUL - 10 YDUMP = 0 canvas = shapes.Drawing(500, 100) # canvas.add(shapes.Rect(0,0, 500, PAGE_HEIGHT, fillColor=colors.yellow)) backcolor=colgen(0.6, 0.8, 1.0) forecolor=colgen(0.2, 0.5, 0.8) def hexstr(x): s = [] for c in x: s.append("%02x" % ord(c)) return " ".join(s) my_y = 0 shift = 0 last_x = 0 while t: bkcol = backcolor.next() proto,fields = t.pop() l = Label() l.setText(proto.name) l.boxAnchor = 'w' l.boxStrokeColor = colors.gray bc = colors.Color(bkcol[0], bkcol[1], bkcol[2] ) l.boxFillColor = bc l.setOrigin(XSTART, (YDUMP-y)*YMUL) canvas.add(l) my_y = y for fname, fval, fdump in fields: y += 1.5 col = forecolor.next() l = Label() l.boxAnchor = 'w' l.setText(fname.name) l.setOrigin(XSTART + (0.1 * XMUL), (YDUMP-y)*YMUL) canvas.add(l) if fval is not None: if len(fval) > 24: fval = fval[:21]+"..." else: fval="" l = Label() l.setText(fval) xlabel, ylabel = XSTART+(1.5*XMUL), (YDUMP-y)*YMUL l.setOrigin(xlabel, ylabel) l.boxStrokeWidth = 2 l.boxAnchor = 'e' canvas.add(l) first = True while fdump: dmp, fdump = fdump[:larg-shift],fdump[larg-shift:] l = Label() l.boxAnchor = 'w' l.fontName = 'Courier' l.boxFillColor = colors.Color(bkcol[0], bkcol[1], bkcol[2]) l.boxStrokeColor = colors.Color(col[0], col[1], col[2]) l.boxStrokeWidth = 2 xdump, ydump = XDSTART+ last_x * 0.06*XMUL, (YDUMP-my_y)*YMUL l.setOrigin(xdump, ydump) h = hexstr(dmp) l.setText(h) canvas.add(l) if first: link = shapes.Line(xdump, ydump, xlabel, ylabel, strokeColor=colors.Color(col[0], col[1], col[2]), strokeWidth=1) canvas.add(link) first = False shift += len(dmp) last_x += len(h) +1 if shift >= larg: shift = 0 last_x = 0 my_y += 2 y += 2 scale = 0.7 canvas.shift(0, y * YMUL*scale) canvas.height = min(y * YMUL *scale , PAGE_HEIGHT*0.80) canvas.scale(scale, scale) # para = Paragraph('<a name="hex%d"/>'%p.number + \ # '<a href="#summary%d">(%d) %s</a>' % (p.number, p.number, p.description), styles['Normal']) # story.append([[para, Spacer(1,10), canvas]]) para = Paragraph('<a href="#summary%d">(%d) %s</a>' % (p.number, p.number, p.description), styles['Normal']) story.append([[para, Spacer(1,10), canvas]]) t = Table(story) t.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.1, colors.black), ('BOX', (0,0), (-1,-1), 0.1, colors.black), ])) return [t]
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() #若需要显示中文,需要先注册一个中文字体 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'
legend.fontSize = 8 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))
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