def _draw_scatter_plot(self, cur_drawing, x_start, y_start, x_end, y_end): """Draw a scatter plot on the drawing with the given coordinates.""" scatter_plot = LinePlot() # set the dimensions of the scatter plot scatter_plot.x = x_start scatter_plot.y = y_start scatter_plot.width = abs(x_start - x_end) scatter_plot.height = abs(y_start - y_end) scatter_plot.data = self.display_info scatter_plot.joinedLines = 0 # set the axes of the plot x_min, x_max, y_min, y_max = self._find_min_max(self.display_info) scatter_plot.xValueAxis.valueMin = x_min scatter_plot.xValueAxis.valueMax = x_max scatter_plot.xValueAxis.valueStep = (x_max - x_min) / 10.0 scatter_plot.yValueAxis.valueMin = y_min scatter_plot.yValueAxis.valueMax = y_max scatter_plot.yValueAxis.valueStep = (y_max - y_min) / 10.0 self._set_colors_and_shapes(scatter_plot, self.display_info) cur_drawing.add(scatter_plot)
def getHumPlot(): drawing = Drawing(400, 200) humedad = [getHumedad()] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = humedad ydlabel = Label() ydlabel.setText("Humedad (%)") ydlabel.angle = 90 ydlabel.setOrigin(20, 120) lp.joinedLines = 2 lp.lines[0].symbol = makeMarker('Circle') lp.lines[0].strokeColor = colors.blue lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 30 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 100 #lp.xValueAxis.visible=False #lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis drawing.add(lp) drawing.add(ydlabel) drawing.add(String(130, 200, "Gráfico de humedad", fontSize=16)) return drawing
def line_plot(O, xy_max, data, label_font_size): if (reportlab is None): return from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors lp = LinePlot() lp.x = 40 lp.y = 40 lp.height = 120 lp.width = 120 lp.data = [[(0, 0), (xy_max, xy_max)], data] lp.lines[0].strokeColor = colors.Color(*[0.8] * 3) lp.lines[0].strokeWidth = 0.5 lp.lines[1].strokeColor = colors.white lp.lines[1].strokeWidth = 0 lp.lines[1].symbol = makeMarker("Circle") lp.lines[1].symbol.strokeWidth = 0.5 lp.joinedLines = 1 lp.strokeColor = colors.Color(*[0.8] * 3) lp.strokeWidth = 1 lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = xy_max lp.xValueAxis.valueSteps = range(xy_max + 1) lp.xValueAxis.strokeWidth = 1 lp.xValueAxis.tickDown = 3 lp.xValueAxis.labels.fontSize = label_font_size lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = xy_max lp.yValueAxis.valueSteps = range(xy_max + 1) lp.yValueAxis.strokeWidth = 1 lp.yValueAxis.tickLeft = 3 lp.yValueAxis.labels.fontSize = label_font_size return lp
def makePlotChart(self, context, width, height, data, xvalues, linecolors): content = [] drawing = Drawing(width, height) plot = LinePlot() plot.x = 0 plot.y = self.padding plot.height = height - 2 * self.padding plot.width = width plot.data = data plot.joinedLines = 1 plot.lineLabelFormat = '%2.0f' i = 0 for color in linecolors : plot.lines[i].strokeColor = colors.HexColor(color) i+=1 if xvalues : plot.xValueAxis.valueSteps = xvalues drawing.add(plot) content.append( drawing ) return content
def line_plot(O, xy_max, data, label_font_size): if (reportlab is None): return from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors lp = LinePlot() lp.x = 40 lp.y = 40 lp.height = 120 lp.width = 120 lp.data = [[(0,0),(xy_max,xy_max)], data] lp.lines[0].strokeColor = colors.Color(*[0.8]*3) lp.lines[0].strokeWidth = 0.5 lp.lines[1].strokeColor = colors.white lp.lines[1].strokeWidth = 0 lp.lines[1].symbol = makeMarker("Circle") lp.lines[1].symbol.strokeWidth = 0.5 lp.joinedLines = 1 lp.strokeColor = colors.Color(*[0.8]*3) lp.strokeWidth = 1 lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = xy_max lp.xValueAxis.valueSteps = range(xy_max+1) lp.xValueAxis.strokeWidth = 1 lp.xValueAxis.tickDown = 3 lp.xValueAxis.labels.fontSize = label_font_size lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = xy_max lp.yValueAxis.valueSteps = range(xy_max+1) lp.yValueAxis.strokeWidth = 1 lp.yValueAxis.tickLeft = 3 lp.yValueAxis.labels.fontSize = label_font_size return lp
def line_plot(final_dis_angle): drawing = Drawing() data = [final_dis_angle] lp = LinePlot() lp.x = 0 lp.y = -120 lp.height = 300 lp.width = 450 lp.data = data lp.joinedLines = 0 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black # lp.xValueAxis.valueMin = 0 # lp.xValueAxis.valueMax = 5 # lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' # lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 7 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) return drawing
def _draw_scatter_plot(self, cur_drawing, x_start, y_start, x_end, y_end): """Draw a scatter plot on the drawing with the given coordinates.""" scatter_plot = LinePlot() # set the dimensions of the scatter plot scatter_plot.x = x_start scatter_plot.y = y_start scatter_plot.width = abs(x_start - x_end) scatter_plot.height = abs(y_start - y_end) scatter_plot.data = self.display_info scatter_plot.joinedLines = 0 # set the axes of the plot x_min, x_max, y_min, y_max = self._find_min_max(self.display_info) scatter_plot.xValueAxis.valueMin = x_min scatter_plot.xValueAxis.valueMax = x_max scatter_plot.xValueAxis.valueStep = (x_max - x_min) / 10.0 scatter_plot.yValueAxis.valueMin = y_min scatter_plot.yValueAxis.valueMax = y_max scatter_plot.yValueAxis.valueStep = (y_max - y_min) / 10.0 self._set_colors_and_shapes(scatter_plot, self.display_info) cur_drawing.add(scatter_plot)
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 add_linePlotChart(self, title, data, size=(PAGE_WIDTH-100, 300)): __chart_width, __chart_heigh = size[0], size[1] __draw = Drawing(__chart_width, __chart_heigh) __draw.add(String(20, __chart_heigh-10, title, fontName="chsFont",fontSize=18, fillColor=colors.black)) #LinePlot基本属性 lp = LinePlot() lp.x, lp.y = 25, 50 lp.width, lp.height = __chart_width-50, __chart_heigh-100 lp.data = data lp.joinedLines = 1 #X轴配置 lp.xValueAxis.valueMin = min([x[0] for x in data[0]]) lp.xValueAxis.valueMax = max([x[0] for x in data[0]]) valueRange = lp.xValueAxis.valueMax - lp.xValueAxis.valueMin lp.xValueAxis.valueStep = valueRange / 10.0 #Y轴配置 yValueMin = min([x[1] for x in data[0]]) yValueMax = max([x[1] for x in data[0]]) yValueRange = yValueMax - yValueMin if (yValueMin-yValueRange/2) > 0: lp.yValueAxis.valueMin = yValueMin - yValueRange/2 else: lp.yValueAxis.valueMin = yValueMin lp.yValueAxis.valueMax = yValueMax+ 0.01 + yValueRange/3 #+1避免当y轴最大值和最小值相等时valuseStep为0,导致绘图库计算y轴格数时出现除零错误 lp.yValueAxis.valueStep = (lp.yValueAxis.valueMax - lp.yValueAxis.valueMin)/10 lp.yValueAxis.visibleGrid = 1 lp.yValueAxis.gridStrokeWidth = 0.5 lp.yValueAxis.gridStrokeColor = colors.gray __draw.add(lp) self.__content.append(__draw)
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 drawline(self,width,height,*args): drawing=Drawing(width,height) ab=LinePlot() ab.x=180 ab.y=0 ab.height=200 ab.width=420 ab.xValueAxis._valueMin = 0 ab.yValueAxis._valueMin=0 ab.joinedLines=1 ab.data=[args] ab.lines[0].strokeColor=colors.red drawing.add(ab) return drawing
def addElectricPrice(canvas_param, pos_x, pos_y, width, height): # 电价数据 data = electricityPriceData # 定义各曲线标签 # data_name = ['一般工商业电价(1-10千伏)', '大工业电价(1-10千伏)', '一般工商业电价(35-110千伏)', '大工业电价(35-110千伏)'] data_name = ['一般工商业电价(35-110千伏)'] c = canvas_param # c.setFont("song", 10) drawing = Drawing(width=width, height=height) lp = LinePlot() # lp.x = 50 # lp.y = 50 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 # 定义各曲线颜色 lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.darkgreen lp.lines[3].strokeColor = colors.black for i in range(0, len(data)): lp.lines[i].name = data_name[i] # lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5) lp.lines[i].strokeWidth = 1 # lp.lineLabelFormat = '%2.0f' # lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 24 lp.xValueAxis.valueSteps = [n for n in range(0, 24, 1)] lp.xValueAxis.labelTextFormat = lambda x: str(x) lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 50 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10) # 将画布添加到pdf中 renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y) return c
def drawrelationshipcs(can, resultsbuffer): can.setFont("Helvetica", 24) sec_title = "System Heat Balance" can.drawString(25, 750, sec_title) desc_text = "The following figure shows the relationship between the chilled water" \ " system operating efficiency and the cooling load. As the figure shows, with " \ "the Cooling load ranges between 800 RT to 1100 RT, the efficiency hovers between " \ "0.75/RT to 0.91KW/RT." stylesheet = getSampleStyleSheet() paragraph = Paragraph(desc_text, stylesheet['Normal']) aW, aH = 500, 600 w, h = paragraph.wrap(aW, aH) if w <= aW and h <= aH: paragraph.drawOn(can, 25, 700) drawing = Drawing(600, 400) data = [((801, 0.7), (903, 0.8), (799, 0.84), (1002, 0.97), (1101, 0.89)), ((987, 0.98), (1007, 1.1), (1102, 0.98), (987, 0.95), (908, 0.89))] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 250 lp.width = 400 lp.data = data lp.joinedLines = 0 lp.lines.symbol = makeMarker('FilledCircle') # lp.lines.symbol = makeMarker('Circle') # lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 1200 lp.xValueAxis.valueSteps = [ 0.00, 200.00, 400.00, 600.00, 800.00, 1000.00, 1200.00 ] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 1.2 lp.yValueAxis.valueSteps = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2 ] drawing.add(lp) drawing.drawOn(can, 50, 350) can.showPage()
def test_23_linePlotCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append( Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1, 1 * inch)) d = Drawing(400, 200) data = [ [(1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)], ] lp = LinePlot() lp.x = 5 lp.y = 5 lp.height = 190 lp.width = 390 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') d.add(lp) elements.append(d) doc.build(elements)
def line_plot(data, elements): drawing = Drawing(0, 400) # for indices lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing)
def genLinePlot(objLogFileReader, columnName): """生成单个测试场景Log数据的指定数值列的折线图""" plotWidth, plotHeight = 500, 180 d = Drawing(plotWidth, plotHeight) title = columnName d.add( String(0, plotHeight - 10, title, fontSize=12, fillColor=colors.black)) data = objLogFileReader.getLinePlotData(columnName) lp = LinePlot() lp.x, lp.y = 50, 25 lp.width, lp.height = plotWidth - 50, plotHeight - 50 lp.data = data lp.joinedLines = 1 lp.lines[0].strokeColor = colors.blue lp.lines[0].strokeWidth = 1 #设置图表x轴的标尺步长、数据标签文本格式等属性 lp.xValueAxis.valueMin = min([x[0] for x in data[0]]) lp.xValueAxis.valueMax = max([x[0] for x in data[0]]) xValueRange = lp.xValueAxis.valueMax - lp.xValueAxis.valueMin lp.xValueAxis.valueStep = xValueRange / 10.0 lp.xValueAxis.labelTextFormat = myUtil.seconds2Str #设置图表y轴的标尺步长、数据标签文本格式等属性 yValueMin = min([x[1] for x in data[0]]) yValueMax = max([x[1] for x in data[0]]) yValueRange = yValueMax - yValueMin if (yValueMin - yValueRange / 2) > 0: lp.yValueAxis.valueMin = yValueMin - yValueRange / 2 else: lp.yValueAxis.valueMin = yValueMin lp.yValueAxis.valueMax = yValueMax + 0.01 + yValueRange / 3 #+1避免当y轴最大值和最小值相等时valuseStep为0,导致绘图库计算y轴格数时出现除零错误 lp.yValueAxis.valueStep = (lp.yValueAxis.valueMax - lp.yValueAxis.valueMin) / 10 lp.yValueAxis.labelTextFormat = '%.2f' lp.yValueAxis.visibleGrid = 1 lp.yValueAxis.gridStrokeWidth = 0.5 lp.yValueAxis.gridStrokeColor = colors.gray d.add(lp) return d
def add_linePlotChart(self, title, data, size=(PAGE_WIDTH - 100, 300)): __chart_width, __chart_heigh = size[0], size[1] __draw = Drawing(__chart_width, __chart_heigh) __draw.add( String(20, __chart_heigh - 10, title, fontName="chsFont", fontSize=18, fillColor=colors.black)) #LinePlot基本属性 lp = LinePlot() lp.x, lp.y = 25, 50 lp.width, lp.height = __chart_width - 50, __chart_heigh - 100 lp.data = data lp.joinedLines = 1 #X轴配置 lp.xValueAxis.valueMin = min([x[0] for x in data[0]]) lp.xValueAxis.valueMax = max([x[0] for x in data[0]]) valueRange = lp.xValueAxis.valueMax - lp.xValueAxis.valueMin lp.xValueAxis.valueStep = valueRange / 10.0 #Y轴配置 yValueMin = min([x[1] for x in data[0]]) yValueMax = max([x[1] for x in data[0]]) yValueRange = yValueMax - yValueMin if (yValueMin - yValueRange / 2) > 0: lp.yValueAxis.valueMin = yValueMin - yValueRange / 2 else: lp.yValueAxis.valueMin = yValueMin lp.yValueAxis.valueMax = yValueMax + 0.01 + yValueRange / 3 #+1避免当y轴最大值和最小值相等时valuseStep为0,导致绘图库计算y轴格数时出现除零错误 lp.yValueAxis.valueStep = (lp.yValueAxis.valueMax - lp.yValueAxis.valueMin) / 10 lp.yValueAxis.visibleGrid = 1 lp.yValueAxis.gridStrokeWidth = 0.5 lp.yValueAxis.gridStrokeColor = colors.gray __draw.add(lp) self.__content.append(__draw)
def test_23_linePlotCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [ [(1,1), (2,2), (2.5,1), (3,3), (4,5)], ] lp = LinePlot() lp.x = 5 lp.y = 5 lp.height = 190 lp.width = 390 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') d.add(lp) elements.append(d) doc.build(elements)
def genLinePlot(objLogFileReader,columnName): """生成单个测试场景Log数据的指定数值列的折线图""" plotWidth,plotHeight = 500,180 d = Drawing(plotWidth,plotHeight) title = columnName d.add(String(0,plotHeight-10,title,fontSize=12,fillColor=colors.black)) data = objLogFileReader.getLinePlotData(columnName) lp = LinePlot() lp.x,lp.y = 50,25 lp.width,lp.height = plotWidth-50,plotHeight-50 lp.data = data lp.joinedLines = 1 lp.lines[0].strokeColor = colors.blue lp.lines[0].strokeWidth = 1 #设置图表x轴的标尺步长、数据标签文本格式等属性 lp.xValueAxis.valueMin = min([x[0] for x in data[0]]) lp.xValueAxis.valueMax = max([x[0] for x in data[0]]) xValueRange = lp.xValueAxis.valueMax - lp.xValueAxis.valueMin lp.xValueAxis.valueStep = xValueRange/10.0 lp.xValueAxis.labelTextFormat = myUtil.seconds2Str #设置图表y轴的标尺步长、数据标签文本格式等属性 yValueMin = min([x[1] for x in data[0]]) yValueMax = max([x[1] for x in data[0]]) yValueRange = yValueMax - yValueMin if (yValueMin-yValueRange/2) > 0: lp.yValueAxis.valueMin = yValueMin - yValueRange/2 else: lp.yValueAxis.valueMin = yValueMin lp.yValueAxis.valueMax = yValueMax+ 0.01 + yValueRange/3 #+1避免当y轴最大值和最小值相等时valuseStep为0,导致绘图库计算y轴格数时出现除零错误 lp.yValueAxis.valueStep = (lp.yValueAxis.valueMax - lp.yValueAxis.valueMin)/10 lp.yValueAxis.labelTextFormat = '%.2f' lp.yValueAxis.visibleGrid = 1 lp.yValueAxis.gridStrokeWidth = 0.5 lp.yValueAxis.gridStrokeColor = colors.gray d.add(lp) return d
from reportlab.graphics.widgets.markers import makeMarker drawing = Drawing(400, 200) data = [ ((1,1), (2,2), (2.5,1), (3,3), (4,5)), ((1,2), (2,3), (2.5,2), (3.5,5), (4,6)) ] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) draw(drawing, 'LinePlot sample')
def addAcTemp(canvas_param, opc_df_today,pos_x, pos_y, width, height): total_df = opc_df_today # 取出 # “室外天气”、 # “冷却侧供水温度”、 # “冷却侧回水温度”、 # “冷冻侧供水温度”、 # “冷冻侧回水温度” total_df_OAT = total_df[total_df.browse_name == 'OA-T'] total_df_CSSWT = total_df[total_df.browse_name == 'CS-SWT'] total_df_CSRWT = total_df[total_df.browse_name == 'CS-RWT'] total_df_FSSWT = total_df[total_df.browse_name == 'FS-SWT'] total_df_FSRWT = total_df[total_df.browse_name == 'FS-RWT'] # 生成5个变量相应的点阵 data_OAT = ExtractPointFromDf_DateX(df_origin=total_df_OAT, date_col='present_value_source_timestamp', y_col='present_value_value') data_CSSWT = ExtractPointFromDf_DateX(df_origin=total_df_CSSWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_CSRWT = ExtractPointFromDf_DateX(df_origin=total_df_CSRWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_FSSWT = ExtractPointFromDf_DateX(df_origin=total_df_FSSWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_FSRWT = ExtractPointFromDf_DateX(df_origin=total_df_FSRWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_origin = [tuple(data_OAT), tuple(data_CSSWT), tuple(data_CSRWT), tuple(data_FSSWT), tuple(data_FSRWT)] # 定义各曲线标签 data_name_origin = ['室外温度', '冷却侧供水温度', '冷却侧回水温度', '冷冻侧供水温度', '冷冻侧回水温度'] # 处理某条线没有数据的情况,若不处理“没有数据”的情况,画线的时候会报错! data = [] data_name = [] for i in range(0, len(data_origin)): if len(data_origin[i]) != 0: data.append(data_origin[i]) data_name.append(data_name_origin[i]) if len(data) == 0: print('函数 addAcTemp:原始df解析后没有想要的温度数据!') return canvas_param c = canvas_param # c.setFont("song", 10) drawing = Drawing(width=width, height=height) lp = LinePlot() # lp.x = 50 # lp.y = 50 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 # 定义各曲线颜色 lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.lightgreen lp.lines[3].strokeColor = colors.orange lp.lines[4].strokeColor = colors.darkgreen for i in range(0, len(data)): lp.lines[i].name = data_name[i] lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5) lp.lines[i].strokeWidth = 0.2 # lp.lineLabelFormat = '%2.0f' # lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 60*60*24 lp.xValueAxis.valueSteps = [n for n in range(0, 60*60*24, 60*60)] lp.xValueAxis.labelTextFormat = lambda x: str(s2t(x))[0:2] lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 50 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10) renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y)
def run(self): def weight_sort(a, b): return cmp(a.getWeight(), b.getWeight()) drawing = Drawing(600, 300) lc = LinePlot() # Determine axis dimensions and create data set maxval = 0 minval = 0 dimension_one_values = [] dimension_two_values = [] dimension_one_answeroptions_as_objects = [] dimension_two_answeroptions_as_objects = [] counter = 0 for question in self.getQuestions(): weights = [int(weight) for weight in question.getAnswerOptionsWeights()] answeroptions = list(question.getAnswerOptions()) # This is used by the legend. Sort on weight. if counter == 0: dimension_one_answeroptions_as_objects = question.getAnswerOptionsAsObjects() dimension_one_answeroptions_as_objects.sort(weight_sort) else: dimension_two_answeroptions_as_objects = question.getAnswerOptionsAsObjects() dimension_two_answeroptions_as_objects.sort(weight_sort) # Minmax lmin = min(weights) lmax = max(weights) if lmin < minval: minval = lmin if lmax > maxval: maxval = lmax # Data for user, answer in question.answers.items(): value = answer.get('value', None) weight = None if value is not None: # Lookup the integer weight of this answer if value in answeroptions: index = answeroptions.index(value) weight = weights[index] # Always add to the list. ReportLab deals with None. if counter == 0: dimension_one_values.append(weight) else: dimension_two_values.append(weight) counter += 1 # Set minmax absmax = max(abs(minval), abs(maxval)) * 1.1 lc.xValueAxis.valueMin = -absmax lc.xValueAxis.valueMax = absmax lc.yValueAxis.valueMin = -absmax lc.yValueAxis.valueMax = absmax # Zip to create data data = [zip(dimension_one_values, dimension_two_values)] if not len(data[0]): return lc.x = 0 lc.y = 0 # Misc setup lc.height = 300 lc.width = 300 lc.data = data lc.joinedLines = 0 lc.fillColor = None lc.lines[0].strokeColor = colors.red lc.lines[0].symbol = makeMarker('FilledCircle') # Add a grid grid = DoubleGrid() lc.background = grid setupGrid(lc) lc.background = None # Finetune the grid grid.grid0.strokeWidth = 0.2 grid.grid1.strokeWidth = 0.2 # Add to drawing else it overwrites the center Y axis drawing.add(grid) # Add a Y axis to pass through the origin yaxis = YValueAxis() yaxis.setPosition(lc.width/2, 0, lc.height) yaxis.configure([(0,-absmax),(0,absmax)]) yaxis.strokeColor = colors.blue drawing.add(yaxis) # Color X-Axis lc.xValueAxis.strokeColor = colors.green drawing.add(lc) # Legend for Dimension One drawing.add(String(lc.width+20, lc.height-12, 'Dimension One (X-Axis):', fontName='Helvetica', fontSize=12, fillColor=colors.green)) legend = Legend() legend.alignment = 'right' legend.x = lc.width + 20 legend.y = lc.height - 20 legend.fontName = 'Helvetica' legend.fontSize = 12 legend.columnMaximum = 7 items = [] for ob in dimension_one_answeroptions_as_objects: items.append( ( StringWidget(ob.getWeight()), ob() ) ) legend.colorNamePairs = items drawing.add(legend, 'legend1') # Legend for Dimension Two drawing.add(String(lc.width+20, lc.height/2-12, 'Dimension Two (Y-Axis):', fontName='Helvetica', fontSize=12, fillColor=colors.blue)) legend = Legend() legend.alignment = 'right' legend.x = lc.width + 20 legend.y = lc.height/2 - 20 legend.fontName = 'Helvetica' legend.fontSize = 12 legend.columnMaximum = 7 items = [] for ob in dimension_two_answeroptions_as_objects: items.append( ( StringWidget(ob.getWeight()), ob() ) ) legend.colorNamePairs = items drawing.add(legend, 'legend2') # Write out data = drawing.asString('png') request = self.REQUEST response = request.RESPONSE response.setHeader('Content-Type', 'image/png') response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId()) response.setHeader('Content-Length', len(data)) response.setHeader('Cache-Control', 's-maxage=0') return data
def generate_certificate(elements): styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catnames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catnames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.7 * inch)) styles = ParagraphStyle( name='Normal', fontName='Helvetica', fontSize=15, alignment=0, ) elements.append(Spacer(1, 0.5* inch)) i = Paragraph(str("Please click on black square to play the video."), styles) elements.append(i) elements.append(platypus.flowables.Macro('canvas.saveState()')) elements.append(platypus.flowables.Macro('canvas.linkURL("fun.mp4",(400,510,410,500),relative=0,thickness=10)')) elements.append(platypus.flowables.Macro('canvas.restoreState()')) return elements
def getPlot(): drawing = Drawing(400, 200) #temps = [((0.5,7), (1.5,1), (2.5,2), (3.5,1), (4.5,3), (5.5,5), (6.5, 10), (7.5,6))] temps = [getTemps()] bc = LinePlot() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = temps #labels yilabel = Label() yilabel.setText("Temperatura (°C)") yilabel.angle = 90 yilabel.setOrigin(20,120) xlabel = Label() xlabel.setText("Días") xlabel.setOrigin(200,20) labelT = Label() labelT.setText("Temperatura") labelT.setOrigin(210,185) labelH = Label() labelH.setText("Humedad") labelH.setOrigin(285,185) bc.xValueAxis.valueMin = 0 bc.xValueAxis.valueMax = 20 bc.xValueAxis.valueSteps = [x for x in range(1,bc.xValueAxis.valueMax)] #bc.xValueAxis.labelTextFormat = '%2.1f' bc.yValueAxis.valueMin = 0 bc.yValueAxis.valueMax = 60 bc.yValueAxis.valueSteps = [0, 10, 20, 30, 40, 50, 60] drawing.add(bc) drawing.add(yilabel) drawing.add(xlabel) drawing.add(Line(170,185,185,185, strokeColor=colors.red)) drawing.add(Line(250,185,265,185, strokeColor=colors.blue)) drawing.add(labelT) drawing.add(labelH) #humedad=[[(0.5, 4), (1.5, 3), (2.5, 4), (3.5, 6), (4.5, 4), (5.5, 2), (6.5, 5), (7.5, 6)]] humedad = [getHumedad()] lp = LinePlot() lp.x = bc.x lp.y = bc.y lp.height = bc.height lp.width = bc.width lp.data = humedad ydlabel = Label() ydlabel.setText("Humedad (%)") ydlabel.angle = -90 ydlabel.setOrigin(lp.x+lp.width+30,lp.y+70) lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('Circle') lp.lines[0].strokeColor=colors.blue lp.lineLabelFormat = '%2.0f' lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = bc.xValueAxis.valueMax lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 100 lp.xValueAxis.visible=False lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis drawing.add(lp) drawing.add(ydlabel) y2Axis = YValueAxis()#Replicate 2nd plot Yaxis in the right y2Axis.setProperties(lp.yValueAxis.getProperties()) y2Axis.setPosition(lp.x+lp.width,lp.y,lp.height) y2Axis.tickRight=5 y2Axis.tickLeft=0 y2Axis.labels.dx = 20 y2Axis.configure(humedad) y2Axis.visible=True drawing.add(y2Axis) return drawing
def generatedReport(self, df, dirReport): #Valores de cajas de texto nom_empre = self.line_nom_empre.text() codigo_text = self.line_cod.text() #Image #pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") fecha = str(datetime.today().strftime('%Y-%m-%d')) address = "Reporte_" + fecha + "_.pdf" path = os.path.join(dirReport, address) path2 = os.path.join(base_path, "cap.jpeg") doc = SimpleDocTemplate(path) #Imagen elements.append(Image(path2, width=1 * inch, height=1 * inch)) #Titulo elements.append( Paragraph('<font >REPORTE DE TEMPERATURA</font>', stylesheet['Title'])) #Descripcion elements.append( Paragraph('<font >DATOS GENERALES</font>', stylesheet['BodyText'])) elements.append( Paragraph( '<font >Empresa: ' + nom_empre + '</font> <font > Código: ' + codigo_text + '</font>', stylesheet['BodyText'])) elements.append( Paragraph('<font >Fecha: ' + fecha + '</font>', stylesheet['BodyText'])) elements.append(Paragraph('<font ></font>', stylesheet['BodyText'])) #Descripcion Ejes elements.append( Paragraph('<font >DESCRIPCIÓN GRÁFICO</font>', stylesheet['BodyText'])) elements.append( Paragraph( '<font > Eje Y = Grados Centigrados / Eje X = Tiempo Minutos</font>', stylesheet['BodyText'])) elements.append( Paragraph( '<font color=blue> -- Sensor #1 --</font> <font color=yellow>-- Sensor #2 --</font> <font color=red>-- Sensor #3 --</font> <font color=green>-- Sensor #4 --</font> <font color=brown>-- Promedio --</font>', stylesheet['BodyText'])) elements.append(Spacer(1, 1 * inch)) #Datos para el Gráfico lista_temp1 = [] lista_temp2 = [] lista_temp3 = [] lista_temp4 = [] lista_total = [] promedio_ = [] data_table = [] cabecera = [] cabecera.append('No') cabecera.append('Fecha') cabecera.append('Hora') cabecera.append('Temp 1') cabecera.append('Temp 2') cabecera.append('Temp 3') cabecera.append('Temp 4') cabecera.append('Tiempo / Minutos') cabecera.append('Promedio') data_table.append(cabecera) const = df['Hora'][0] format = '%H:%M:%S' for index, row in df.iterrows(): diff = (datetime.strptime(str(row['Hora']), format) - datetime.strptime(str(const), format)) / 60 total_minu = round(diff.total_seconds(), 1) var_promedio = (row['Temp1'] + row['Temp2'] + row['Temp3'] + row['Temp4']) / 4 round_promedio = round(var_promedio, 2) c_1 = (total_minu, row['Temp1']) c_2 = (total_minu, row['Temp2']) c_3 = (total_minu, row['Temp3']) c_4 = (total_minu, row['Temp4']) c_5 = (total_minu, round_promedio) lista_temp1.append(c_1) lista_temp2.append(c_2) lista_temp3.append(c_3) lista_temp4.append(c_4) promedio_.append(c_5) array_aux = [] array_aux.append(row['n']) array_aux.append(row['Fecha']) array_aux.append(row['Hora']) array_aux.append(row['Temp1']) array_aux.append(row['Temp2']) array_aux.append(row['Temp3']) array_aux.append(row['Temp4']) array_aux.append(total_minu) array_aux.append(round_promedio) data_table.append(array_aux) lista_total.append(lista_temp1) lista_total.append(lista_temp2) lista_total.append(lista_temp3) lista_total.append(lista_temp4) lista_total.append(promedio_) elements.append(Spacer(1, 1 * inch)) elements.append(Spacer(1, 1 * inch)) drawing = Drawing(400, 200) lp = LinePlot() lp.x = 100 lp.y = 100 lp.height = 300 lp.width = 300 lp.data = lista_total lp.joinedLines = 1 #lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 100 lp.xValueAxis.valueStep = 10 #lp.xValueAxis.valueSteps =listHora_aux lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 180 lp.yValueAxis.valueStep = 5 lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.yellow lp.lines[2].strokeColor = colors.red lp.lines[3].strokeColor = colors.green lp.lines[4].strokeColor = colors.brown drawing.add(lp) elements.append(drawing) #Tabla elements.append( Paragraph('<font >DESCRIPCIÓN TABLA</font>', stylesheet['BodyText'])) elements.append(Paragraph('<font ></font>', stylesheet['BodyText'])) style_table = TableStyle([ ('BACKGROUND', (0, 0), (8, 0), colors.green), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (8, 1000000), 'CENTER'), ('FONTNAME', (0, 0), (-1, 0), 'Courier-Bold') ]) table = Table(data_table) table.setStyle(style_table) elements.append(table) elements.append(Spacer(1, 1 * inch)) elements.append(Spacer(1, 1 * inch)) #Firma #elements.append(Paragraph('<font >Hola</font>', stylesheet['Title'])) elements.append(Spacer(1, 1 * inch)) doc.build(elements) msg = QMessageBox() msg.setWindowTitle("Alerta") msg.setText("Correcta Generación de Reporte !!!") x = msg.exec_()
def addAcPower(canvas_param, opc_df_today, pos_x, pos_y, width, height): total_df = opc_df_today # 取出 # “离心机1号实时功率”、 # “离心机2号实时功率”、 # “螺杆机实时功率” total_df_01P = total_df[total_df.browse_name == 'Chilling_unit1_D1_CH-01-Load'] total_df_02P = total_df[total_df.browse_name == 'Chilling_unit2_D2_CH-02-Load'] total_df_03P = total_df[total_df.browse_name == 'Chilling_unit3_D3_CH-03-Load'] # 生成5个变量相应的点阵 data_01P = ExtractPointFromDf_DateX( df_origin=total_df_01P, date_col='present_value_source_timestamp', y_col='present_value_value') data_02P = ExtractPointFromDf_DateX( df_origin=total_df_02P, date_col='present_value_source_timestamp', y_col='present_value_value') data_03P = ExtractPointFromDf_DateX( df_origin=total_df_03P, date_col='present_value_source_timestamp', y_col='present_value_value') data_origin = [tuple(data_01P), tuple(data_02P), tuple(data_03P)] # 定义各曲线标签 data_name_origin = ['离心机1号实时功率', '离心机2号实时功率', '螺杆机实时功率'] # 处理某条线没有数据的情况,若不处理“没有数据”的情况,画线的时候会报错! data = [] data_name = [] for i in range(0, len(data_origin)): if len(data_origin[i]) != 0: data.append(data_origin[i]) data_name.append(data_name_origin[i]) if len(data) == 0: print('函数 addAcTemp:原始df解析后没有想要的冷机功率数据!') return canvas_param c = canvas_param # c.setFont("song", 10) drawing = Drawing(width=width, height=height) lp = LinePlot() # lp.x = 50 # lp.y = 50 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 # 定义各曲线颜色 lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.lightgreen lp.lines[3].strokeColor = colors.orange lp.lines[4].strokeColor = colors.darkgreen for i in range(0, len(data)): lp.lines[i].name = data_name[i] lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5) lp.lines[i].strokeWidth = 0.05 # lp.lineLabelFormat = '%2.0f' # lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 60 * 60 * 24 lp.xValueAxis.valueSteps = [n for n in range(0, 60 * 60 * 24, 60 * 60)] lp.xValueAxis.labelTextFormat = lambda x: str(s2t(x))[0:2] lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 50 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10) # 将画布添加到pdf中 renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y) return c
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors drawing = Drawing(400, 200) data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) drawing.save(formats=['pdf'], outDir='./pdfs', fnRoot='chart') # c = canvas.Canvas('./pdfs/chart_canvas.pdf') # c.da
def createTimeSeries(self,ser): if self.single_record: return # Time series are available for these quantities. The number indicates their position in the data string series = {'h':0, 'g':1, 'i10':2, 'i100':6, 'tori':3, 'Read10':7} # The time series plot will get added to the 'drawing' object drawing = Drawing(400, 200) # and it is of type 'LinePlot' lp = LinePlot() lp.x = 30 lp.y = 50 lp.height = 125 lp.width = 350 # Record the publication years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['metrics series'].keys()))) lp.data = [] series_data = [] # The maximum value will be used to scale the y axis max_value = 0 # This list will hold the data points for the histogram for year in years: values = map(lambda a: float(a),self.data['metrics series'][str(year)].split(':')) max_value = max(max_value,values[series[ser]]) if ser == 'read10' and year > 1995: series_data.append((year,values[series[ser]])) else: series_data.append((year,values[series[ser]])) lp.data.append(series_data) lp.joinedLines = 1 # Define the line color lp.lines[0].strokeColor = colors.orange # Actual data point will be marked by a filled circle lp.lines.symbol = makeMarker('FilledCircle') lp.strokeColor = colors.black # The extreme values for the x axis lp.xValueAxis.valueMin = years[0] lp.xValueAxis.valueMax = years[-1] # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lp.xValueAxis.labels.dx = -6 lp.xValueAxis.labels.dy = -18 # and rotate the labels by 90 degrees lp.xValueAxis.labels.angle = 90 lp.xValueAxis.valueSteps = years # For both axes values will be displayed as integers lp.xValueAxis.labelTextFormat = '%2.0f' lp.yValueAxis.labelTextFormat = '%2.0f' # Define the maximum value of the y axis lp.yValueAxis.valueMax = int(math.ceil(float(max_value)/10.0))*10 # Depending on the range of values, set a value step for the y axis if max_value > 10000: lp.yValueAxis.valueStep = 1000 elif max_value > 1000: lp.yValueAxis.valueStep = 100 else: lp.yValueAxis.valueStep = 10 # The y axis always starts at 0 lp.yValueAxis.valueMin = 0 # Now add the line plot to the 'drawing' object drawing.add(lp) # Finally add the appropriate title to the plot drawing.add(String(200,190,"%s index time series" % ser, textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
def generate_certificate(elements): style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.red), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red), ('BOX', (0, 0), (-1, -1), 0.50, colors.green), ('BACKGROUND', (0, 0), (-1, -1), colors.blue), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = "RGB" styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) return elements
def genLPDrawing(data, data_note, width=letter[0]*0.8, height=letter[1]*0.25, timeAxis='day', y_min_zero=False): """ 函数功能:生成Drawing之用 :return: """ drawing = Drawing(width=width, height=height) lp = LinePlot() # lp.x = 50 # lp.y = 50 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 # 定义颜色集 barFillColors = [ colors.red, colors.green, colors.blue, colors.darkgoldenrod, colors.pink, colors.purple, colors.lightgreen, colors.darkblue, colors.lightyellow, colors.fidred, colors.greenyellow, colors.gray, colors.white,colors.blueviolet, colors.lightgoldenrodyellow] for i in range(0, len(data)): lp.lines[i].name = data_note[i] lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5) lp.lines[i].strokeWidth = 0.2 lp.lines[i].strokeColor = barFillColors[i] # lp.lineLabelFormat = '%2.0f' # lp.strokeColor = colors.black x_min = data[0][0][0] x_max = data[0][-1][0] lp.xValueAxis.valueMin = x_min lp.xValueAxis.valueMax = x_max if timeAxis=='day': step = int(((x_max - x_min) / (60 * 60 * 24)) / 30) + 1 lp.xValueAxis.valueSteps = [n for n in range(int(x_min), int(x_max), 60 * 60 * 24 * step)] lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x)[0:10]) lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 50 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] elif timeAxis=='quarter': step = int(((x_max - x_min)/0.25) / 30) + 1 lp.xValueAxis.valueSteps = [n for n in range(int(x_min), int(x_max), int(math.ceil(0.25 * step)))] lp.xValueAxis.labelTextFormat = lambda x: convertValue2Quarter(x) lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 elif timeAxis=='year': lp.xValueAxis.valueSteps = [n for n in range(int(x_min), int(x_max), 1)] lp.xValueAxis.labelTextFormat = lambda x: str(x) lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 elif timeAxis=='month': lp.xValueAxis.valueSteps = list(map(lambda x:x[0],data[0])) lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x))[0:7] lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 drawing.add(lp) add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-20) return drawing
def chart(distance, altitude, angle, next_point, qn): data1 = [] data2 = [] data3 = [] alt_min = alt_max = alt_min_all = alt_max_all = altitude[0] for i in range(len(distance)): data1.append((distance[i], altitude[i])) if distance[i] <= next_point: if alt_min > altitude[i]: alt_min = altitude[i] if alt_max < altitude[i]: alt_max = altitude[i] if alt_min_all > altitude[i]: alt_min_all = altitude[i] if alt_max_all < altitude[i]: alt_max_all = altitude[i] _alt_min = int(alt_min / 100) * 100 _alt_max = int(alt_max / 100) * 100 + 100 _alt_min_all = int(alt_min_all / 100) * 100 _alt_max_all = int(alt_max_all / 100) * 100 + 100 rate = (_alt_max_all - _alt_min_all) / 15 for i in range(len(distance)): data2.append((distance[i], angle[i] * rate + _alt_min_all)) # data = (data1, data2) data = (data1, ) drawing = Drawing(400, 0) lp = LinePlot() lp.x = 25 lp.y = 20 lp.height = 400 lp.width = 815 lp.data = data lp.joinedLines = 1 # lp.lines[0].symbol = makeMarker('FilledCircle') # lp.lines[1].symbol = makeMarker('Circle') lp.lines[0].strokeColor = HexColor(0x808080) lp.lines[0].strokeWidth = 3 lp.lines[1].strokeColor = HexColor(0x808080) lp.lines[1].strokeWidth = 1 lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 10 lp.xValueAxis.valueSteps = list(range(1, 11)) + [next_point] lp.xValueAxis.labelTextFormat = '%.1f' # lp.xValueAxis.strokeColor = HexColor(0x808080) lp.yValueAxis.valueMin = _alt_min_all lp.yValueAxis.valueMax = _alt_max_all lp.yValueAxis.valueSteps = [alt_min_all, alt_max_all] + list( range(_alt_min_all, _alt_max_all + 1, 100)) lp.yValueAxis.labelTextFormat = '%d' drawing.add(lp) x = 815 * next_point / 10 + 25 drawing.add(Line(x, 20, x, 400 + 20, strokeColor=HexColor(0x808080))) prev_distance = distance[0] prev_alt = altitude[0] for i in range(1, len(distance)): high = max(prev_alt, altitude[i]) low = min(prev_alt, altitude[i]) for alt in range(int(low) // 3 + 1, int(high) // 3 + 1): rate = (alt * 3 - low) * 1.0 / (high - low) d = (distance[i] - prev_distance) * rate + prev_distance x = 815 * d / 10 + 25 if low == prev_alt: drawing.add( Line(x, 30 + 20, x, 80 + 20, strokeColor=HexColor(0x000000))) else: drawing.add( Line(x, 10 + 20, x, 30 + 20, strokeColor=HexColor(0x808080))) prev_distance = distance[i] prev_alt = altitude[i] drawing.drawOn(pdfFile, 0, 0) pdfFile.line(0, 0, 0, 100) pdfmetrics.registerFont( TTFont(fontname, '/usr/share/fonts/ipa-gothic/ipag.ttf')) pdfmetrics.registerFont( TTFont("waree", '/usr/share/fonts/thai-scalable/Waree.ttf')) pdfFile.setFont(fontname, 40) pdfFile.drawString(1 * cm, 19.5 * cm, str(round(Q[qn]["distance"], 1))) pdfFile.setFont(fontname, 50) pdfFile.drawString(7 * cm, 19.5 * cm, str(Q[qn]["limit_time"])) pdfFile.setFont(fontname, 50) pdfFile.drawString(13.5 * cm, 19.5 * cm, str(round(Q[qn]["distance_to_next_pc"], 1))) pdfFile.setFont(fontname, 50) pdfFile.drawString(19 * cm, 19.5 * cm, str(Q[qn]["plan_time"])) pdfFile.setFont(fontname, 40) pdfFile.drawString(25 * cm, 19.5 * cm, str(Q[qn - 1]["plan_time"])) # pdfFile.drawString(25*cm, 19.5*cm, str(int(Q[qn]["no"]))) direction = "%s %s %s" % (round(Q[qn]["lap_distance"], 1), Q[qn]["direction"], Q[qn]["road"]) y = 16 * cm y = put_text(pdfFile, y, direction, 110, 0.5 * cm) # pdfFile.drawString(0*cm, 17*cm, direction) # y = 14*cm if Q[qn]["comment1"]: y = put_text(pdfFile, y, Q[qn]["comment1"], 90, font=fontname) y = put_text(pdfFile, y, "%s%s" % (Q[qn]["signal"], Q[qn]["comment2"]), 60, font=fontname) y = put_text( pdfFile, y, "%d - %d - %d - %d" % (altitude[0], alt_min, alt_max, alt_max_all), 50) pdfFile.setFont(fontname, 50) pdfFile.drawString(25 * cm, 1.0 * cm, str(round(Q[qn]["distance_to_drop"], 1))) pdfFile.showPage()