def __init__(self, width=A4[0], height=A4[0] / 2, left_margin=0, right_margin=0, top_margin=0, bottom_margin=0, label_font_size=10, label_font_name='simsun'): self.label_font_size = label_font_size self.label_font_name = label_font_name self.width = width self.height = height # self.chart_width = self.width # self.chart_height = self.height self.chart_width = self.chart_height = min( self.width - left_margin - right_margin, self.height - top_margin - bottom_margin) self.chart = Pie() # self.chart.x = 0 # self.chart.y = 0 self.chart.x = (self.width - self.chart_width) / 2 self.chart.y = (self.height - self.chart_height) / 2 self.chart.width = self.chart_width self.chart.height = self.chart_height self.title = Label()
def getTalkRect(self, startTime, duration, trackId, text): "Return shapes for a specific talk" g = Group() y_bottom = self.scaleTime(startTime + duration) y_top = self.scaleTime(startTime) y_height = y_top - y_bottom if trackId is None: #spans all columns x = self._colLeftEdges[1] width = self.width - self._colWidths[0] else: #trackId is 1-based and these arrays have the margin info in column #zero, so no need to add 1 x = self._colLeftEdges[trackId] width = self._colWidths[trackId] lab = Label() lab.setText(text) lab.setOrigin(x + 0.5 * width, y_bottom + 0.5 * y_height) lab.boxAnchor = 'c' lab.width = width lab.height = y_height lab.fontSize = 6 r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan) g.add(r) g.add(lab) #now for a label # would expect to color-code and add text return g
def graphout_stackedBar(data, labels, X, Y): drawing = Drawing(X*inch, Y*inch) bar = VerticalBarChart() bar.x = 50 bar.y = 50 bar.width = (X-2)*inch bar.height = (Y-1)*inch bar.data = data bar.bars.strokeWidth = 0 bar.categoryAxis.style='stacked' bar.categoryAxis.labels.boxAnchor = 'ne' bar.categoryAxis.labels.dx = -2 bar.categoryAxis.labels.dy = -2 bar.categoryAxis.labels.angle = 45 bar.categoryAxis.categoryNames = labels # ensure bar chart and legend coloring matches for i in range(len(data)): bar.bars[i].fillColor = colorList[i] # Create a title for the y-axis yLabel = Label() yLabel.setOrigin(0, 50) # for reference, the graph origin is (50, 50) yLabel.boxAnchor = 'c' yLabel.angle = 90 yLabel.setText('Data Storage [GB]') yLabel.fontSize=16 yLabel.dy = 1.25*inch drawing.add(yLabel) drawing.add(bar) return drawing
def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) # Width and height of chart. self.width = 772 self.height = 280 # Add title self._add(self, Label(), name='title', validate=None, desc=None) self.title._text = 'Simple Bar Chart' self.title.fontSize = 24 self.title.fontName = "Calibri" # Position Title self.title.x = 386 self.title.y = 240 # Add Bar chart to the Drawing. self._add(self, VerticalBarChart(), name="chart", validate=None, desc=None) # Bar Chart Position self.chart.x = 150 self.chart.y = 20 # Bar Chart Dimensions self.chart.width = 400 self.chart.height = 150 # Data will be sent from RML. However, defaults can be initialized here. self.chart.data = [] self.chart.barLabelArray = None # Ticks invisible on X-Axis self.chart.categoryAxis.visibleTicks = 0 # X-Axis visible self.chart.categoryAxis.visibleAxis = 1 # X-Axis labels. Data will be sent from RML. However, defaults can be initialized here. self.chart.categoryAxis.categoryNames = [] # Vertically display X-Axis labels self.chart.categoryAxis.labels.angle = 90 # Offset for X-Axis Labels self.chart.categoryAxis.labels.dy = -15 # Show bars one on top of the other. # self.chart.categoryAxis.style = 'stacked' # Y-Axis Visible self.chart.valueAxis.visibleAxis = 1 self.chart.valueAxis.labelTextFormat = None # Avoid assuming minimum value as origin self.chart.valueAxis.avoidBoundSpace = (5, 0) # Offset for Y-Axis Labels self.chart.valueAxis.labels.dx = -8 # Add Description Label for Y-Axis self._add(self, Label(), name='yAxistitle', validate=None, desc=None) # Label properties self.yAxistitle.angle = 90 self.yAxistitle._text = 'Y axis text' self.yAxistitle.x = 110 self.yAxistitle.y = 80 # Color the bars self.chart.bars[0].fillColor = toColor(0xae1a09) self.chart.bars[0].strokeColor = toColor( 0xae1a09) # Color(.290196, .427451, .741176, 1) self.chart.bars[1].fillColor = toColor(0x0079c1) self.chart.bars[1].strokeColor = toColor(0x0079c1)
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 __init__(self,title,ylable): self.drawing = Drawing(400,200) self.lp = LinePlot() self.lp.x = 50 self.lp.y = 50 self.lp.height = 125 self.lp.width = 300 #title设置 self.title = Label() self.title.fontSize = 12 title_text = title self.title._text = title_text self.title.x = 190 self.title.y = 190 self.title.textAnchor ='middle' #x轴设置 self.Xlabel = Label() self.Xlabel._text = 'time' self.Xlabel.fontSize = 12 self.Xlabel.x = 380 self.Xlabel.y = 30 self.Xlabel.textAnchor ='middle' #y轴设置 self.Ylabel = Label() self.Ylabel._text = ylable self.Ylabel.fontSize = 12 self.Ylabel.x = 40 self.Ylabel.y = 190 self.Ylabel.textAnchor ='middle'
def __init__(self, xList, yList, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.width = 80 * 1.2 * 2.5 self.height = 60 * 0.8 * 2.5 self._add(self, VerticalBarChart(), name='chart', validate=None, desc=None) self.chart.y = 11.2 * 2 self.chart.x = 20 * 2 #self.chart.data = [[0.05, 0.05, 0.1, 0.1, 0.05, 0.05, 0.955555]] self.chart.data = yList self.chart.width = self.width * 0.75 self.chart.height = self.height * 0.75 self.chart.bars.strokeColor = None self.chart.bars[0].fillColor = colors.blue maxTmp = (max(yList[0]) / 1000) * 1000 valueStepsTmp = [] for i in [0.2, 0.4, 0.6, 0.8, 1.0]: valueStepsTmp.append(i * maxTmp) self.chart.valueAxis.valueSteps = valueStepsTmp self.chart.categoryAxis.visibleTicks = False self.chart.barLabels.fontSize = 2.8 * 2.5 self.chart.barLabels.fontName = 'Helvetica-Bold' self.chart.valueAxis.labels.fontSize = 2.8 * 2.5 self.chart.valueAxis.labels.fontName = 'Helvetica-Bold' xListNew = [] interval = (max([int(item) for item in xList]) - min([int(item) for item in xList])) / 10 for i in range(len(xList)): if i % interval == 0: xListNew.append(xList[i]) else: xListNew.append('') self.chart.categoryAxis.categoryNames = xListNew self.chart.categoryAxis.labels.fontSize = 2.8 * 2.5 self.chart.categoryAxis.labels.fontName = 'Helvetica-Bold' self._add(self, Label(), name='XLabel', validate=None, desc='Percentage') self.XLabel.fontSize = 4.4 * 2 self.XLabel.fontName = 'Helvetica-Bold' self.XLabel._text = 'Read length' self.XLabel.dx = 48 * 2.5 self.XLabel.dy = 2 self._add(self, Label(), name='YLabel', validate=None, desc='Percentage') self.YLabel.fontSize = 4.4 * 2 self.YLabel.fontName = 'Helvetica-Bold' self.YLabel._text = 'Counts' self.YLabel.dx = 0.8 self.YLabel.dy = 32 * 2.5 self.YLabel.angle = 90
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 addScale(drawing, xmap, y, start, end, tickLen=10, dx=3, dy=6, textAnchor='middle', boxAnchor='s', fontSize=12, strokeWidth=1, strokeColor=colors.black, scale=1.0, format='%ibp'): x1 = xmap(start) x2 = xmap(end) line = Line(x1+dx,y,x2-dx,y, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(line) leftTick = Line(x1+dx,y-0.5*tickLen,x1+dx,y+0.5*tickLen, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(leftTick) rightTick = Line(x2-dx,y-0.5*tickLen,x2-dx,y+0.5*tickLen, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(rightTick) label = Label() label.setOrigin(0.5*(x1+x2), y+dy) distance = float(end-start)/scale label.setText(format % (distance/scale)) label.fontSize = fontSize label.textAnchor = textAnchor label.boxAnchor = boxAnchor drawing.add(label)
def getTalkRect(self, startTime, duration, trackId, text): "Return shapes for a specific talk" g = Group() y_bottom = self.scaleTime(startTime + duration) y_top = self.scaleTime(startTime) y_height = y_top - y_bottom if trackId is None: #spans all columns x = self._colLeftEdges[1] width = self.width - self._colWidths[0] else: #trackId is 1-based and these arrays have the margin info in column #zero, so no need to add 1 x = self._colLeftEdges[trackId] width = self._colWidths[trackId] lab = Label() lab.setText(text) lab.setOrigin(x + 0.5*width, y_bottom+0.5*y_height) lab.boxAnchor = 'c' lab.width = width lab.height = y_height lab.fontSize = 6 r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan) g.add(r) g.add(lab) #now for a label # would expect to color-code and add text return g
def _test0(self): "Perform original test function." pdfPath = outputfile('test_charts_textlabels.pdf') c = Canvas(pdfPath) label = Label() demoLabel = label.demo() demoLabel.drawOn(c, 0, 0) c.save()
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 _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 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 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 write_label(label, width, height, person): text = "\n".join((person['name'], person['addresses'][0])) lab = Label() lab.setOrigin(8, height - 5) lab.fontSize = 14 lab.setText(text) lab.boxAnchor = 'nw' label.add(lab)
def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) # Width and height of chart. self.width = 772 self.height = 280 # Add title self._add(self, Label(), name='title', validate=None, desc=None) self.title._text = 'Simple Pie Chart' self.title.fontSize = 24 self.title.fontName = "Calibri" # Position Title self.title.x = 386 self.title.y = 240 # Add Bar chart to the Drawing. self._add(self, Pie(), name="chart", validate=None, desc=None) # Bar Chart Dimensions self.chart.width = 150 self.chart.height = 150 self.chart.slices[2].popout = 15 # Bar Chart Position self.chart.x = (self.width - self.chart.width) / 2 self.chart.y = 20 # Data will be sent from RML. However, defaults can be initialized here. self.chart.data = [] # Sector Labels. Data will be sent from RML. However, defaults can be initialized here. self.chart.labels = [] # Start angle for Pie Chart. 90 indicates 12'o Clock position. self.chart.startAngle = 90 # Pie Chart direction. self.chart.direction = 'clockwise'
def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.lineLabelFormat = None self.chart.xLabel = 'X Axis' self.chart.y = 30 self.chart.yLabel = 'Y Axis' self.chart.yValueAxis.labelTextFormat = '%d' self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self,0,name='preview',validate=None,desc=None)
def make_x_axis(self, x_label, x_min, x_max, x_step): self._add(self, Label(), name='XLabel', validate=None, desc="The label on the horizontal axis") self.XLabel.fontName = 'Helvetica' self.XLabel.fontSize = 10 self.XLabel.x = 22 self.XLabel.y = 45 self.XLabel.textAnchor = 'middle' self.XLabel.maxWidth = 500 self.XLabel.height = 20 self.XLabel._text = x_label self.chart.xValueAxis = XValueAxis() self.chart.xValueAxis.labels.boxAnchor = 'autox' self.chart.xValueAxis.valueMin = x_min self.chart.xValueAxis.valueMax = x_max self.chart.xValueAxis.valueStep = x_step self.chart.xValueAxis.labels.fontName = "Helvetica" self.chart.xValueAxis.labels.fontSize = 10 self.chart.xValueAxis.visibleTicks = 1 self.chart.xValueAxis.labels.rightPadding = 0 self.chart.xValueAxis.labels.dx = 1
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 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 draw_travels(self): for p in self.world.packets: if self.detailed: txt = p.command() else: txt = "(%d) %s" % (p.number, p.description) last_action = (0,0) for ts in p.trip: action = self.packet_actions[ts.action] if ts.actor not in self.verticals: self.verticals[ts.actor] = self.verticals[ts.actor.node] x2,y2 = self.verticals[ts.actor], -ts.time*self.yzoom if action.sprite: self.sequence_diagram.add(shapes.Circle(x2, y2, action.size, fillColor=action.color, strokeWidth=1 )) if action.travel: if action.travel_desc: # self.sequence_diagram.add(shapes.String((last_action[0] + x)/2,(last_action[1]+y)/2, label, fill=colors.black, textAnchor = 'middle')) x1, y1 = last_action[0], last_action[1] l = Label() l.setText(txt) l.angle = atan2((y2-y1)/2, (x2-x1))*360.0/pi l.dy = 10 l.setOrigin((x1 + x2)/2,(y1+y2)/2) self.sequence_diagram.add(l) #anchor = Paragraph('<a name="diagram%d"/>' %p.number, styles['Normal']) self.sequence_diagram.add(shapes.Line(last_action[0],last_action[1],x2,y2, strokeColor=colors.black, strokeWidth=1)) self.max_y = min(y2, self.max_y, last_action[1]) last_action = (x2,y2)
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 __init__(self, width=200, height=150, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self._add(self, SpiderChart(), name='chart', validate=None, desc="The main chart") self.chart.width = 90 self.chart.height = 90 self.chart.x = 45 self.chart.y = 25 self.chart.strands[0].fillColor = color01 self.chart.strands[1].fillColor = color02 self.chart.strands[2].fillColor = color03 self.chart.strands[3].fillColor = color04 self.chart.strands[4].fillColor = color05 self.chart.strands[5].fillColor = color06 self.chart.strands[6].fillColor = color07 self.chart.strands[7].fillColor = color08 self.chart.strands[8].fillColor = color09 self.chart.strands[9].fillColor = color10 self.chart.strandLabels.fontName = 'Helvetica' self.chart.strandLabels.fontSize = 6 self.chart.fillColor = backgroundGrey self.chart.data = [(125, 180, 200), (100, 150, 180)] self.chart.labels = ['North', 'South', 'Central'] self._add(self, Label(), name='Title', validate=None, desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor = 'middle' self._add(self, Legend(), name='Legend', validate=None, desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment = 'right' self._add(self, 0, name='preview', validate=None, desc=None)
def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self.chart.startAngle = -90 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.Legend.columnMaximum = 10 self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 20 self.background.y = 20 self.chart.slices.popout = 5 self.background.height = 110 self.background.width = 110 self._add(self,0,name='preview',validate=None,desc=None)
def addPointyCompoundFeature(drawing, xmap, y, gene, strokeColor=None, fillColor=colors.blue, intronColor=colors.blue, glyph=PointyBlock, height=12, utrHeight=6, rise=8, labeldy=10, fontSize=10, textAnchor='middle', boxAnchor='s'): """Adds a pointy compound feature to the drawing. This is typically several exons joined by zig-zag lines with an arrow showing strand.""" if gene.strand=='+': x1,x2 = xmap(gene.start), xmap(gene.end) else: x2,x1 = xmap(gene.start), xmap(gene.end) y = y+height/2 y1 = y line = Line(x1,y1,x2,y1,strokeColor=intronColor) drawing.add(line) for exon in gene: if exon.strand=='+': x1,x2 = xmap(exon.start), xmap(exon.end) else: x2,x1 = xmap(exon.start), xmap(exon.end) g = glyph() g.x = x1 g.y = y if exon.kind.lower()=='utr': g.height = utrHeight else: g.height = height g.length = x2-x1 g.fillColor = fillColor if strokeColor: g.strokeColor = strokeColor else: g.strokeColor = fillColor g.fontSize = fontSize drawing.add(g) label = Label() label.setText(gene.name) x = 0.5*(gene.start+gene.end) label.setOrigin(x,y) label.dy = labeldy label.textAnchor = textAnchor label.boxAnchor = boxAnchor drawing.add(label)
def colorTest(self): from reportlab.graphics.shapes import Rect from reportlab.graphics.charts.textlabels import Label self.colorRangeStatic(130) dim=25 width = self.PAGE_WIDTH-150 inrow = 8 #int(width/dim) height = int(len(self.colors)/inrow) if len(self.colors)%inrow > 0: height +=1 height *= dim drawing = Drawing(width, height) for i,col in enumerate(self.colors): x = (i%inrow)*dim y = int(i/inrow)*dim rec = Rect(x=x,y=y,width=dim,height=dim) rec.fillColor = col drawing.add(rec) lab = Label() lab.x=x+dim/2 lab.y=y+dim/2 lab.setText('%d'%i) drawing.add(lab) return drawing
def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.add(VerticalBarChart(), name='chart') self.add(Label(), name='ylabel') self.add(Label(), name='xlabel') self.chart.x = 110 self.chart.y = -80 self.chart.width = self.width - self.chart.x - 10 self.chart.height = self.height - self.chart.y - 10 self.chart.barSpacing = 1 self.ylabel.fontName = 'Helvetica' self.ylabel.fontSize = 15 self.ylabel.angle = 90 self.ylabel.x = 80 self.ylabel.y = (self.chart.y + self.chart.height * 0.5) self.xlabel.fontSize = 15 self.xlabel.height = 0 self.xlabel.maxWidth = 100 self.xlabel.fontName = 'Helvetica' self.xlabel.x = (self.chart.x + self.chart.width * 1.2) self.xlabel.y = -80
def _makeProtoLabel(self): "Return a label prototype for further modification." protoLabel = Label() protoLabel.dx = 0 protoLabel.dy = 0 protoLabel.boxStrokeWidth = 0.1 protoLabel.boxStrokeColor = colors.black protoLabel.boxFillColor = colors.yellow # protoLabel.text = 'Hello World!' # Does not work as expected. return protoLabel
def genLayers2(ls): #ls =(titre, taille) c = ['#ffeea0', '#ff88ff', '#bbd5e8'] length = 4 * cm # ls = np.asarray(ls) l = [] for i in range(len(ls)): l.append((ls[i][0], ls[i][1])) ls = np.asarray(l, dtype=np.str) d = Drawing(4 * cm, 100) xpos = 0 ls[:, 1] = layersize2(ls[:, 1]) tickness = ls[:, 1].astype(np.float32) for i in range(len(ls)): lab = Label() lab.textAnchor = 'middle' color = c[0] labelTxt = str(ls[:, 0][i]) if '+' in labelTxt: color = c[1] elif '-' in labelTxt: color = c[2] lab.setText(ls[:, 0][i]) if i > 0: d.add( Rect(xpos, np.cumsum(tickness)[i - 1], length, tickness[i], fillColor=colors.HexColor(color))) lab.setOrigin(xpos + 2 * cm, np.cumsum(tickness)[i - 1] + tickness[i] / 2) else: d.add( Rect(xpos, 0, length, tickness[i], fillColor=colors.HexColor(color))) lab.setOrigin(xpos + 2 * cm, tickness[i] / 2) d.add(lab) return d
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 make_title(self, title, font="Helvetica"): self._add(self, Label(), name="Title", validate=None, desc="The title at the top of the chart") self.Title.fontName = font self.Title.fontSize = 14 self.Title.x = 265 self.Title.y = 225 self.Title._text = title self.Title.maxWidth = 500 self.Title.height = 20 self.Title.textAnchor = "middle"
def make_title(self, title): self._add(self, Label(), name='Title', validate=None, desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 14 self.Title.x = 265 self.Title.y = 225 self.Title._text = title self.Title.maxWidth = 500 self.Title.height = 20 self.Title.textAnchor = 'middle'
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 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 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
legend.y = h - 30 legend.boxAnchor = 'sw' legend.colorNamePairs = [(self.Color[i], names[i]) for i in range(len(names))] legend.fontName = 'Helvetica' 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))
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
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.data = [pos_pers, neg_pers, nor_pos_pers, nor_neg_pers] print lp.data lp.joinedLines = 1 lp.lines.symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.2f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 2100 lp.xValueAxis.labelTextFormat = '%2.0f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 100 lp.yValueAxis.valueStep = 10 xlbl = Label() xlbl.setText("No. of Genes") xlbl.setOrigin(310, 72) ylbl = Label() ylbl.setText("Percentage\n (%)") ylbl.setOrigin(28, 260) lp.lines[0].strokeColor = colors.darkgreen lp.lineLabels[0].strokeColor = colors.darkgreen lp.lines[1].strokeColor = colors.tomato lp.lineLabels[1].strokeColor = colors.tomato lp.lines[2].strokeColor = colors.aquamarine lp.lineLabels[2].strokeColor = colors.aquamarine lp.lines[3].strokeColor = colors.purple lp.lineLabels[3].strokeColor = colors.purple
def makeSummary(self, stype): logger.debug('StartQT4::makeSummary(%s)' % stype) pinfo = self.imageViews[-1].getSummaryDemographics() if pinfo is None: return reportname = self.imageViews[-1].getReportName()+'.pdf' filename = QtGui.QFileDialog.getSaveFileName(self, directory=reportname, filter='PDF Files *.pdf(*.pdf);;All Files *(*)') #filename = QtGui.QFileDialog.getSaveFileName(self, filter='PDF Files *.pdf(*.pdf);;All Files *(*)') if len(filename) == 0: return doc = SimpleDocTemplate(str(filename), pagesize=A4, rightMargin=1.5*cm, leftMargin=2*cm, topMargin=2*cm, bottomMargin=3*cm) elements = [] #data = pinfo.items() for iv in self.imageViews: vt = iv.getVelocityText() if stype == 'BOTH' or stype == iv.getViewShortName(): pinfo.append(vt) t=Table(pinfo, rowHeights=12) t.setStyle(TableStyle([('BACKGROUND',(1,1),(-2,-2),colors.green), ('TEXTCOLOR',(0,0),(1,-1),colors.black), ('ALIGNMENT', (0,0),(0,-1), 'RIGHT')])) elements.append(t) for iv in self.imageViews: if stype == 'BOTH' or stype == iv.getViewShortName(): drawing = Drawing(400, 280) cd = iv.getDataPointer() vt = iv.getVelocityText() pinfo.append(vt) #ydata = cd.getCOMYScaled(False, 'mm').tolist() ydata = cd.getCOMYScaled(True, 'mm').tolist() xPlaneFit = cd.getYPlaneFit(units='mm', bothAxes=True).tolist() vdata = cd.getVelocitySlopeScaled(units='mm', bothAxes=True) gdata = [ydata, xPlaneFit] if vdata is not None: gdata.append(vdata.tolist()) title = Label() title.setOrigin(150, 240) title.setText(iv.getViewName()) ylabel = Label() ylabel.setOrigin(0, 100) ylabel.angle = 90 ylabel.setText("Millimeters") xlabel = Label() xlabel.setOrigin(70, 0) xlabel.setText("Seconds") lp = LinePlot() lp.height = 230 lp.width = 400 lp.data = gdata lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green #lp.xValueAxis.xLabel = "Seconds" drawing.add(title) drawing.add(ylabel) drawing.add(xlabel) drawing.add(lp) elements.append(drawing) doc.build(elements, onFirstPage=self.pdfHeaderFooter, onLaterPages=self.pdfHeaderFooter)
def addCompoundFeature(drawing, xmap, y, gene, strokeColor=None, fillColor=colors.blue, intronColor=colors.blue, intronWidth=0.5, glyph=Block, height=12, utrHeight=6, labeldy=10, fontSize=10, textAnchor='middle', boxAnchor='s'): """Adds a compund feature to the drawing. A compound feature is typically several exons joined by zig-zag lines.""" rise = height + utrHeight intronStarts = [None] intronEnds = [] heights = [] for exon in gene: x1,x2 = xmap(exon.start), xmap(exon.end) kind = exon.kind.lower() if kind in ['exon', 'utr']: intronStarts.append(exon.end) intronEnds.append(exon.start) g = glyph() g.x = x1 g.y = y+height/2 if exon.kind.lower()=='exon': g.height = height heights.append(height) else: g.height = utrHeight heights.append(utrHeight) g.length = x2-x1 g.fillColor = fillColor if strokeColor: g.strokeColor = strokeColor else: g.strokeColor = fillColor g.fontSize = fontSize drawing.add(g) for i,(intronStart,intronEnd) in enumerate(zip(intronStarts[1:], intronEnds[1:])): x1 = xmap(intronStart) x2 = xmap(0.5*(intronStart+intronEnd)) x3 = xmap(intronEnd) # if abs(x3-x1)<3: continue # print intronStart,intronEnd,heights[i],heights[i+1] y1 = y+heights[i]/2+height/2 y2 = y+rise y3 = y+heights[i+1]/2+height/2 line1 = Line(x1,y1,x2,y2,strokeColor=intronColor,strokeWidth=intronWidth) line2 = Line(x2,y2,x3,y3,strokeColor=intronColor,strokeWidth=intronWidth) drawing.add(line1) drawing.add(line2) # Draw arrows if xmap.flipped: signum = -1 else: signum = 1 if gene.strand=='+': x1 = xmap(gene.end) x2 = x1 + signum*15 x3 = x1 + signum*10 y1 = y + 0.5*height y2 = y + 0.75*height y3 = y + 0.25*height line1 = Line(x1,y1,x2,y1,strokeColor=intronColor,strokeWidth=intronWidth) line2 = Line(x2,y1,x3,y2,strokeColor=intronColor,strokeWidth=intronWidth) line3 = Line(x2,y1,x3,y3,strokeColor=intronColor,strokeWidth=intronWidth) drawing.add(line1) drawing.add(line2) drawing.add(line3) else: x1 = xmap(gene.start) x2 = x1 - signum*15 x3 = x1 - signum*10 y1 = y + 0.5*height y2 = y + 0.75*height y3 = y + 0.25*height line1 = Line(x1,y1,x2,y1,strokeColor=intronColor,strokeWidth=intronWidth) line2 = Line(x2,y1,x3,y2,strokeColor=intronColor,strokeWidth=intronWidth) line3 = Line(x2,y1,x3,y3,strokeColor=intronColor,strokeWidth=intronWidth) drawing.add(line1) drawing.add(line2) drawing.add(line3) # if gene has attribute name... label = Label() label.setText(gene.name) pos = 0.5*(gene.start+gene.end) x = xmap(pos) label.setOrigin(x,y) label.dy = labeldy label.textAnchor = textAnchor label.boxAnchor = boxAnchor drawing.add(label)
def _rawDraw(self, x, y): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS from reportlab.graphics.charts.axes import XCategoryAxis,YValueAxis from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.charts.barcharts import VerticalBarChart self.originX = x self.originY = y self._setScale([self.dataBar]) (x1, y1, Width, Height) = self._getGraphRegion(x, y) #Build the graph self.drawing = Drawing(self.width, self.height) #Size of the Axis SizeXaxis = 14 countSteps = int(self.valueMax / self.valueStep) SizeYaxis = 0.0 for n in range(countSteps + 1): eachValue = self.valueMin + n * self.valueStep textString = self._customSecondsLabelFormat( eachValue ) SizeYaxis = max(SizeYaxis, self._stringWidth(textString, STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) ) bc = VerticalBarChart() SizeYaxis += bc.valueAxis.tickLeft bc.x = x1 - x + SizeYaxis bc.y = y1 - y + SizeXaxis bc.height = Height - SizeXaxis bc.width = Width - SizeYaxis self.graphCenterX = bc.x + bc.width/2 self.graphCenterY = bc.y + bc.height/2 if self.validData: # add valid data to chart bc.data = self.dataBar bc.categoryAxis.categoryNames = self.dataNames # axis values bc.valueAxis.valueMin = self.valueMin bc.valueAxis.valueMax = self.valueMax bc.valueAxis.valueStep = self.valueStep # add value labels above bars bc.barLabelFormat = self._customSecondsLabelFormat bc.barLabels.dy = 0.08*inch bc.barLabels.fontSize = 6 else: # no valid data bc.data = [ (0, ), ] bc.categoryAxis.categoryNames = [ '' ] bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 1 bc.valueAxis.valueStep = 1 Nodata = Label() Nodata.fontSize = 12 Nodata.angle = 0 Nodata.boxAnchor = 'c' Nodata.dx = self.graphCenterX Nodata.dy = self.graphCenterY Nodata.setText("NO VALID DATA") self.drawing.add(Nodata) # chart formatting (R,G,B) = VeriwaveYellow bc.bars[0].fillColor = colors.Color(R,G,B) bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat # axis labels bc.categoryAxis.labels.boxAnchor = 'c' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.labels.fontSize = 8 # add chart self.drawing.add(bc) #Adjust the labels to be the center of the graph self._drawLabels(self.title, "", "") # Add Legend in upper right corner legendHeight = 9 legendX = bc.x + 5 legendY = bc.y + bc.height - 12 self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[0].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'MIN', fontName='Helvetica', fontSize=8)) legendY -= legendHeight self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[1].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'MAX', fontName='Helvetica', fontSize=8)) legendY -= legendHeight self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[2].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'AVG', fontName='Helvetica', fontSize=8)) legendY -= legendHeight
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)
lab.boxStrokeColor = colors.green lab.setText('Some\nMulti-Line\nLabel') d.add(lab) """) from reportlab.graphics import shapes from reportlab.graphics.charts.textlabels import Label d = Drawing(200, 100) # mark the origin of the label d.add(Circle(100,90, 5, fillColor=colors.green)) lab = Label() lab.setOrigin(100,90) lab.boxAnchor = 'ne' lab.angle = 45 lab.dx = 0 lab.dy = -20 lab.boxStrokeColor = colors.green lab.setText('Some\nMulti-Line\nLabel') d.add(lab) draw(d, 'Label example') disc("""
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 _drawLabels(self, Title, xAxis, yAxis): self.graphCenterX = self.width/2 self.graphCenterY = self.height/2 Label_Xaxis = Label() Label_Xaxis.fontSize = 7 Label_Xaxis.angle = 0 Label_Xaxis.dx = self.graphCenterX - 50 Label_Xaxis.dy = 0 Label_Xaxis.boxAnchor = 's' Label_Xaxis.setText(xAxis) self.drawing.add(Label_Xaxis) Label_Yaxis = Label() Label_Yaxis.fontSize = 7 Label_Yaxis.angle = 90 Label_Yaxis.boxAnchor = 'n' Label_Yaxis.dx = -5 Label_Yaxis.dy = self.graphCenterY Label_Yaxis.setText(yAxis) self.drawing.add(Label_Yaxis) Label_Graph = Label() Label_Graph.fontSize = 10 Label_Graph.angle = 0 Label_Graph.boxAnchor = 'n' Label_Graph.dx = self.graphCenterX - 50 Label_Graph.dy = self.height Label_Graph.setText(Title) self.drawing.add(Label_Graph)
def 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)
lp.data = [accuracy_list] print lp.data lp.joinedLines = 1 lp.lines.symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.2f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.labelTextFormat = '%2.0f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 104 lp.yValueAxis.valueStep = 10 xlbl = Label() xlbl.setText("No. of Clusters") xlbl.setOrigin(310, 53) xlbl1 = Label() xlbl1.setText("No. Of Clusters Vs Accuracy") xlbl1.setOrigin(310, 25) ylbl = Label() ylbl.setText("Accuracy\n (%)") ylbl.setOrigin(28, 260) lp.lines[0].strokeColor = colors.purple lp.lineLabels[0].strokeColor = colors.purple d.add(lp)