def sample4d(): "Sample drawing, xvalue/yvalue axes, y connected to top of x." drawing = Drawing(400, 200) data = [(10, 20, 30, 42)] yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) xAxis = XValueAxis() xAxis._length = 300 xAxis.joinAxis = yAxis xAxis.joinAxisMode = 'top' xAxis.configure(data) drawing.add(xAxis) drawing.add(yAxis) return drawing
def sample5d(): "Sample drawing, xvalue/yvalue axes, y connected at left of x." drawing = Drawing(400, 200) data = [(10, 20, 30, 42)] xAxis = XValueAxis() xAxis.setPosition(50, 50, 300) xAxis.configure(data) yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.joinAxis = xAxis yAxis.joinAxisMode = 'left' yAxis.configure(data) drawing.add(xAxis) drawing.add(yAxis) return drawing
def sample6b(): "Sample drawing, xcat/yvalue axes, x connected at bottom of y." drawing = Drawing(400, 200) data = [(10, 20, 30, 42)] yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) xAxis = XCategoryAxis() xAxis._length = 300 xAxis.configure(data) xAxis.joinAxis = yAxis xAxis.joinAxisMode = 'bottom' xAxis.categoryNames = ['Beer', 'Wine', 'Meat', 'Cannelloni'] xAxis.labels.boxAnchor = 'n' drawing.add(xAxis) drawing.add(yAxis) return drawing
def sample4c1(): "xvalue/yvalue axes, without drawing axis lines/ticks." drawing = Drawing(400, 200) data = [(10, 20, 30, 42)] yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) yAxis.visibleAxis = 0 yAxis.visibleTicks = 0 xAxis = XValueAxis() xAxis._length = 300 xAxis.joinAxis = yAxis xAxis.joinAxisMode = 'bottom' xAxis.configure(data) xAxis.visibleAxis = 0 xAxis.visibleTicks = 0 drawing.add(xAxis) drawing.add(yAxis) return drawing
def sample1(): "Sample drawing containing two unconnected axes." from reportlab.graphics.shapes import _baseGFontNameB drawing = Drawing(400, 200) data = [(10, 20, 30, 42)] xAxis = XCategoryAxis() xAxis.setPosition(75, 75, 300) xAxis.configure(data) xAxis.categoryNames = ['Beer', 'Wine', 'Meat', 'Cannelloni'] xAxis.labels.boxAnchor = 'n' xAxis.labels[3].dy = -15 xAxis.labels[3].angle = 30 xAxis.labels[3].fontName = _baseGFontNameB yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) drawing.add(xAxis) drawing.add(yAxis) return drawing
def sample1(): "Sample drawing containing two unconnected axes." from reportlab.graphics.shapes import _baseGFontNameB drawing = Drawing(400, 200) data = [(10, 20, 30, 42)] xAxis = XCategoryAxis() xAxis.setPosition(75, 75, 300) xAxis.configure(data) xAxis.categoryNames = ['Beer','Wine','Meat','Cannelloni'] xAxis.labels.boxAnchor = 'n' xAxis.labels[3].dy = -15 xAxis.labels[3].angle = 30 xAxis.labels[3].fontName = _baseGFontNameB yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) drawing.add(xAxis) drawing.add(yAxis) return drawing
def axes_demo(): drawing = shapes.Drawing(width=500, height=300) data = [(5, 10, 15, 20), (10, 17, 25, 31)] x_axis = XCategoryAxis() x_axis.setPosition(100, 100, 350) x_axis.configure(data, barWidth=None) x_axis.categoryNames = ['Python', 'Ruby', 'C++', 'Haskell', 'Java'] x_axis.labels.boxAnchor = 'n' x_axis.labels[0].angle = 45 x_axis.labels[0].fontName = 'Times-Bold' x_axis.labels[1].fontName = 'Courier' x_axis.labels[1].fontSize = 16 drawing.add(x_axis) y_axis = YValueAxis() y_axis.setPosition(75, 75, 150) y_axis.configure(data) drawing.add(y_axis) renderPDF.drawToFile(drawing, 'axes_demo.pdf')
drawing = Drawing(400, 200) data = [(10, 20, 30, 40), (15, 22, 37, 42)] xAxis = XCategoryAxis() xAxis.setPosition(75, 75, 300) xAxis.configure(data) xAxis.categoryNames = ['Beer', 'Wine', 'Meat', 'Cannelloni'] xAxis.labels.boxAnchor = 'n' xAxis.labels[3].dy = -15 xAxis.labels[3].angle = 30 xAxis.labels[3].fontName = 'Times-Bold' yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) drawing.add(xAxis) drawing.add(yAxis) draw(drawing, 'Two isolated axes') disc("Here is the code that created them: ") eg(""" from reportlab.graphics import shapes from reportlab.graphics.charts.axes import XCategoryAxis,YValueAxis drawing = Drawing(400, 200)
def generateGraphs(self, x, y): (x1, y1, Width, Height) = self._getGraphRegion(x, y) #Draw Axes yVAxis = YValueAxis() #If we got numeric X vals, we use a ValueAxis, otherwise CategoryAxis. if len(self.x_vals) > 0: if isinstance(self.x_vals[0], str): xVAxis = XCategoryAxis() else: xVAxis = XValueAxis() else: return -1 (y_min, y_max, y_step) = self.getValueAxisScale(yVAxis, [self.y_vals]) if y_min == -1 and y_min == -1 and y_step == -1: return -1 (self.valueMin, self.valueMax, self.valueStep) = (y_min, y_max, y_step) (SizeXaxis, SizeYaxis) = self.getSizes() #lot of ugliness in here to get the split chart working :| if self.betweenSplitsF == True: if self.numSplits == 0: self.tmpYVal = SizeYaxis else: SizeYaxis = self.tmpYVal if self.numSplits > 0: xVAxis.visibleLabels = False xVAxis.visibleTicks = False X_start_pos = x1 - x + SizeYaxis X_width = Width - SizeYaxis - 10 if self.betweenSplitsF == True: if self.numSplits > 0: Y_start_pos = y1 - y + SizeXaxis + (self.numSplits * self.height) - (self.numSplits * 15) else: Y_start_pos = y1 - y + SizeXaxis + (self.numSplits * self.height) Y_height = Height - SizeXaxis + 40 else: Y_start_pos = y1 - y + SizeXaxis + (self.numSplits * self.height) Y_height = Height - SizeXaxis xVAxis.setPosition(X_start_pos, Y_start_pos, X_width) if isinstance(xVAxis, XValueAxis): dataList = [] dataTuple = reduce(lambda a,b: a + (b,), self.x_vals, ()) dataList.append(dataTuple) xVAxis.configure(dataList) xVAxis.labelTextFormat = '%0.' + '%d' % self.xAxisDigits + 'f' else: dataList = [] zerodata = [0 for val in self.x_vals] dataTuple = reduce(lambda a,b: a + (b,), zerodata, ()) dataList.append(dataTuple) xVAxis.configure(dataList) xVAxis.categoryNames = self.x_vals #Ugly hack for setting the labels.dy. Empirical: If there are more than 5 #chars, dy = -35 fits fine (assuming the angle would be > 75,when we have #so long val) maxLen = 0 for val in self.x_vals: valLen = len(val) if valLen > maxLen: maxLen = valLen if maxLen > 5: xVAxis.labels.dy = -35 xVAxis.labels.fontName = 'Helvetica' xVAxis.labels.fontSize = 7 xVAxis.labels.angle = self.xValsDisplayAngle drawLegendF = False if len(self.legendList) > 0: drawLegendF = True drawLabelF = False lblCounts = len(self.x_vals) * len(self.y_vals) if lblCounts <= 30 and self.displayDataLbls == True: drawLabelF = True if len(self.x_vals) == 1: drawLabelF = True #hack to increase chart height to include legend and labels total_height = 0 legendHeight = 0 if drawLegendF == True: #Kludge: We enchroach the space needed for legends by bringing down the #y value by 28 (in drawOn()), we use that space here legendHeight = Y_height + 28 graph_height = Y_height yVAxis.setPosition(X_start_pos, Y_start_pos, Y_height) yVAxis.valueMin = y_min yVAxis.valueMax = y_max yVAxis.valueStep = y_step yVAxis.labels.fontName = 'Helvetica' yVAxis.labels.fontSize = 7 yVAxis.labelTextFormat = '%0.' + '%d' % self.yAxisDigits + 'f' yVAxis.configure(self.y_vals) #will later sync the yVAxis as the ValueAxis of the graph self.drawing.add(xVAxis) if self.numSplits == 0: tmp = self.height self.height = self.origHeight self._drawLabels(self.title, self.x_label, self.y_label) self.height = tmp for graphtype in self.graphList: #Draw only one set of Legends/Labels for any dataset, #even if there are multiple charts drawn for the same dataset if self.labelsDrawnF == True and self.numSplits == 0: drawLabelF = False if self.legendsDrawnF == True and self.numSplits == 0: drawLegendF = False if graphtype == 'Bar': GraphObj = VerticalBarChart() GraphObj.valueAxis = yVAxis self.drawGraph(GraphObj, X_start_pos, Y_start_pos, X_width, graph_height, drawLabelF, drawLegendF, legendHeight) if graphtype == 'Line': GraphObj = HorizontalLineChart() GraphObj.valueAxis = yVAxis self.drawGraph(GraphObj, X_start_pos, Y_start_pos, X_width, graph_height, drawLabelF, drawLegendF, legendHeight)
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 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 generatePdfReport(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. Title="Test Report" PAGE_HEIGHT=defaultPageSize[1] PAGE_WIDTH=defaultPageSize[0] p.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, Title) p.drawString(100,900,"Test Configuration") configuration=request.session["test_configuration"] data=[['Operation','On/Off','Percentage','Keys','Size']] if 'readState' in configuration: readData=[['Read',configuration['readState'],configuration['readPercentage'],configuration['readKeys'],configuration['readSize']]] else: readData=[['Read','0','0','0','0']] data=data+readData if 'writeState' in configuration: writeData=[['Write',configuration['writeState'],configuration['writePercentage'],configuration['writeKeys'],configuration['writeSize']]] else: writeData=[['Write','0','0','0','0']] data=data+writeData if 'updateState' in configuration: updateData=[['Update',configuration['updateState'],configuration['updatePercentage'],configuration['updateKeys'],configuration['updateSize']]] else: updateData=[['Update','0','0','0','0']] data=data+updateData table = Table(data, colWidths=100, rowHeights=20) table.hAlign="CENTER" table.setStyle(TableStyle()) table.wrapOn(p, 300, 800) table.drawOn(p,80,550) p.drawString(80,700,"Test Configuration") p.drawString(80,500,"Test Time : ") p.drawString(200,500,str(t1.getTime()) + " miliseconds " ) p.drawString(80,400,"Test Chart") p.saveState() drawing = Drawing(10, 10) data = [(10, 20, 30, 40), (15, 22, 37, 42)] xAxis = XCategoryAxis() xAxis.setPosition(75, 75, 300) xAxis.configure(data) xAxis.categoryNames = ['Beer', 'Wine', 'Meat', 'Cannelloni'] xAxis.labels.boxAnchor = 'n' xAxis.labels[3].dy = -15 xAxis.labels[3].angle = 30 xAxis.labels[3].fontName = 'Times-Bold' yAxis = YValueAxis() yAxis.setPosition(50, 50, 125) yAxis.configure(data) drawing.add(xAxis) drawing.add(yAxis) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response