def addChromosomes(drawing, chrNames, chrSizes, xmap, ymap, w=0.1*DPI, fillColor=colors.skyblue, strokeColor=colors.skyblue): for i,chrom in enumerate(chrNames): x = xmap(i+1) y = ymap(chrSizes[chrom]) h = ymap(1)-ymap(chrSizes[chrom]) chromosome = Rect(x,y,w,h, strokeColor=strokeColor, fillColor=fillColor) drawing.add(chromosome) topCap = Wedge(x+0.5*w, y+h, 0.5*w, 0, 180, strokeColor=strokeColor, fillColor=fillColor) bottomCap = Wedge(x+0.5*w, y, 0.5*w, 180, 0, strokeColor=strokeColor, fillColor=fillColor) drawing.add(topCap) drawing.add(bottomCap) label = Label() label.setOrigin(xmap(i+1)+w/2, ymap(0)) label.boxAnchor = 's' label.textAnchor = 'middle' label.dx = 0 label.dy = DPI/10 label.setText(chrom) label.fontSize = 36 label.fontName = 'Helvetica' drawing.add(label) chrLength = Label() chrLength.setOrigin(xmap(i+1)+w/2, ymap(chrSizes[chrom])) chrLength.boxAnchor = 'n' chrLength.textAnchor = 'middle' chrLength.dx = 0 chrLength.dy = -DPI/10 chrLength.setText('%iMb' % int(chrSizes[chrom]/1e6)) chrLength.fontSize = 24 chrLength.fontName = 'Helvetica' drawing.add(chrLength)
def _drawLabels(self, Title, xAxis, yAxis): self.graphCenterX = self.width/2 self.graphCenterY = self.height/2 Label_Xaxis = Label() Label_Xaxis.fontSize = 7 Label_Xaxis.angle = 0 Label_Xaxis.dx = self.graphCenterX - 50 Label_Xaxis.dy = 0 Label_Xaxis.boxAnchor = 's' Label_Xaxis.setText(xAxis) self.drawing.add(Label_Xaxis) Label_Yaxis = Label() Label_Yaxis.fontSize = 7 Label_Yaxis.angle = 90 Label_Yaxis.boxAnchor = 'n' Label_Yaxis.dx = -5 Label_Yaxis.dy = self.graphCenterY Label_Yaxis.setText(yAxis) self.drawing.add(Label_Yaxis) Label_Graph = Label() Label_Graph.fontSize = 10 Label_Graph.angle = 0 Label_Graph.boxAnchor = 'n' Label_Graph.dx = self.graphCenterX - 50 Label_Graph.dy = self.height Label_Graph.setText(Title) self.drawing.add(Label_Graph)
def addChromosomes(drawing, chrNames, chrSizes, xmap, ymap, w=0.1 * DPI, fillColor=colors.skyblue, strokeColor=colors.skyblue): for i, chrom in enumerate(chrNames): x = xmap(i + 1) y = ymap(chrSizes[chrom]) h = ymap(1) - ymap(chrSizes[chrom]) chromosome = Rect(x, y, w, h, strokeColor=strokeColor, fillColor=fillColor) drawing.add(chromosome) topCap = Wedge(x + 0.5 * w, y + h, 0.5 * w, 0, 180, strokeColor=strokeColor, fillColor=fillColor) bottomCap = Wedge(x + 0.5 * w, y, 0.5 * w, 180, 0, strokeColor=strokeColor, fillColor=fillColor) drawing.add(topCap) drawing.add(bottomCap) label = Label() label.setOrigin(xmap(i + 1) + w / 2, ymap(0)) label.boxAnchor = 's' label.textAnchor = 'middle' label.dx = 0 label.dy = DPI / 10 label.setText(chrom) label.fontSize = 36 label.fontName = 'Helvetica' drawing.add(label) chrLength = Label() chrLength.setOrigin(xmap(i + 1) + w / 2, ymap(chrSizes[chrom])) chrLength.boxAnchor = 'n' chrLength.textAnchor = 'middle' chrLength.dx = 0 chrLength.dy = -DPI / 10 chrLength.setText('%iMb' % int(chrSizes[chrom] / 1e6)) chrLength.fontSize = 24 chrLength.fontName = 'Helvetica' drawing.add(chrLength)
def getTalkRect(self, startTime, duration, trackId, text): "Return shapes for a specific talk" g = Group() y_bottom = self.scaleTime(startTime + duration) y_top = self.scaleTime(startTime) y_height = y_top - y_bottom if trackId is None: #spans all columns x = self._colLeftEdges[1] width = self.width - self._colWidths[0] else: #trackId is 1-based and these arrays have the margin info in column #zero, so no need to add 1 x = self._colLeftEdges[trackId] width = self._colWidths[trackId] lab = Label() lab.setText(text) lab.setOrigin(x + 0.5*width, y_bottom+0.5*y_height) lab.boxAnchor = 'c' lab.width = width lab.height = y_height lab.fontSize = 6 r = Rect(x, y_bottom, width, y_height, fillColor=colors.cyan) g.add(r) g.add(lab) #now for a label # would expect to color-code and add text return g
def addScale(drawing, xmap, y, start, end, tickLen=10, dx=3, dy=6, textAnchor='middle', boxAnchor='s', fontSize=12, strokeWidth=1, strokeColor=colors.black, scale=1.0, format='%ibp'): x1 = xmap(start) x2 = xmap(end) line = Line(x1+dx,y,x2-dx,y, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(line) leftTick = Line(x1+dx,y-0.5*tickLen,x1+dx,y+0.5*tickLen, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(leftTick) rightTick = Line(x2-dx,y-0.5*tickLen,x2-dx,y+0.5*tickLen, strokeWidth=strokeWidth, strokeColor=strokeColor) drawing.add(rightTick) label = Label() label.setOrigin(0.5*(x1+x2), y+dy) distance = float(end-start)/scale label.setText(format % (distance/scale)) label.fontSize = fontSize label.textAnchor = textAnchor label.boxAnchor = boxAnchor drawing.add(label)
def _drawLabels(self, label, labelCenter, y, width): """ Draw the label given in a given area originating at (x,y) with width 'width' """ fontName = 'Times-Roman' fontSize = 10 #Limit the length of the label to the boundaries of the chartAreaWidth strWidth = self._stringWidth(label, fontName, fontSize) #Calculate the area taken by one character oneCharWidth = self._stringWidth(label[0], fontName, fontSize) #If the given string needs more size, reduce the string to a length which fits #in the given area if strWidth > width: maxPossibleLen = int(width/oneCharWidth) label = label[:maxPossibleLen] strWidth = self._stringWidth(label, fontName, fontSize) x = (labelCenter - ((strWidth)/2)) Label_Graph = Label() Label_Graph.fontName = fontName Label_Graph.fontSize = fontSize #Label_Graph.angle = 0 Label_Graph.boxAnchor = 'n' Label_Graph.x = x Label_Graph.y = y Label_Graph.setText(label) self.drawing.add(Label_Graph)
def draw(self): # general widget bits w = float(self.length) h = float(self.height) g = shapes.Group() body = shapes.Polygon( [self.x-0.5*w, self.y-0.5*w, self.x-0.5*w, self.y+0.5*w, self.x+0.5*w, self.y], fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=self.strokeWidth) g.add(body) if self.label: b = g.getBounds() s = Label() s.setText(self.label) s.setOrigin(self.x+0.5*w, self.y-h/2+b[3]-b[1]+4) s.boxAnchor = self.boxAnchor s.textAnchor = self.textAnchor s.fontName = 'Helvetica' s.fontSize = self.fontSize s.angle = self.labelAngle g.add(s) return g
def graphout_stackedBar(data, labels, X, Y): drawing = Drawing(X*inch, Y*inch) bar = VerticalBarChart() bar.x = 50 bar.y = 50 bar.width = (X-2)*inch bar.height = (Y-1)*inch bar.data = data bar.bars.strokeWidth = 0 bar.categoryAxis.style='stacked' bar.categoryAxis.labels.boxAnchor = 'ne' bar.categoryAxis.labels.dx = -2 bar.categoryAxis.labels.dy = -2 bar.categoryAxis.labels.angle = 45 bar.categoryAxis.categoryNames = labels # ensure bar chart and legend coloring matches for i in range(len(data)): bar.bars[i].fillColor = colorList[i] # Create a title for the y-axis yLabel = Label() yLabel.setOrigin(0, 50) # for reference, the graph origin is (50, 50) yLabel.boxAnchor = 'c' yLabel.angle = 90 yLabel.setText('Data Storage [GB]') yLabel.fontSize=16 yLabel.dy = 1.25*inch drawing.add(yLabel) drawing.add(bar) return drawing
def 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 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 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 addLabel(drawing, x, y, text, fontName='Helvetica', fontSize=11, dy=0, angle=0, boxAnchor='sw', textAnchor='start'): """Add a label to the drawing. This interface here is inconsistent in that it requires pixel coords. FIX This just sets convenient defaults for Label.""" label = Label() label.setText(text) label.setOrigin(x, y) label.fontName = fontName label.fontSize = fontSize label.boxAnchor = boxAnchor label.textAnchor = textAnchor label.dy = dy label.angle = angle drawing.add(label)
def 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 addAxis(drawing, xmap, y, strokeWidth=1, minorStrokeWidth=0.5, tickDir='down', autoTicks=False, nTicks=20, tickLen=5, fontSize=10, nMinorTicks=80, minorTickLen=2, angle=0, dx=0, dy=-2, textAnchor='middle', boxAnchor=None, scale=1.0, format='%i'): """Add a horizontal axis to the drawing. To do: Round tick positions """ line = Line(xmap.x0, y, xmap.x1, y, strokeWidth=strokeWidth) drawing.add(line) if not boxAnchor: if tickDir=='down': boxAnchor = 'n' else: boxAnchor = 's' signum = {'up': -1, 'down': 1}[tickDir] if nTicks>0: ticks = tick_generator(xmap.start, xmap.end, n=nTicks, convert=int) for p in ticks: x = xmap(p) line = Line(x, y, x, y-signum*tickLen, strokeWidth=strokeWidth) drawing.add(line) s = Label() s.setOrigin(x, y-signum*tickLen) s.setText(format % (p/scale)) s.dx = dx s.dy = signum*dy s.fontName = 'Helvetica' s.fontSize = fontSize s.textAnchor = textAnchor s.boxAnchor = boxAnchor s.angle = angle drawing.add(s) minorticks = tick_generator(xmap.start, xmap.end, n=nMinorTicks, convert=int) for p in minorticks: x = xmap(p) line = Line(x, y, x, y-signum*minorTickLen, strokeWidth=minorStrokeWidth) drawing.add(line)
def simple_label(): drawing = shapes.Drawing(width=400, height=200) drawing.add(shapes.Rect(200, 100, 10, 10, fillColor=colors.red)) x = 50 angle = 0 for item in range(3): label = Label() label.setOrigin(200, 100) label.boxAnchor = 'se' label.angle = angle #label.boxStrokeColor = colors.black label.setText('ReportLab label') drawing.add(label) x += 25 angle += 45 renderPDF.drawToFile(drawing, 'simple_label.pdf')
def border(): draw = Drawing(1, 1) rect = Polygon(points=[ -12, cm / 6, (PAGE_WIDTH - (RIGHT_MARGIN + LEFT_MARGIN)), cm / 6, PAGE_WIDTH - (RIGHT_MARGIN + LEFT_MARGIN), -1 * (PAGE_HEIGHT - (TOP_MARGIN + BOTTOM_MARGIN + cm / 2)), -12, -1 * (PAGE_HEIGHT - (TOP_MARGIN + BOTTOM_MARGIN + cm / 2)) ], strokeColor=Color(*charts.BG_COLOR)) rect.fillColor = Color(*charts.BG_COLOR, 0.1) draw.add(rect) draw.add(Circle(100, 90, 5, fillColor=colors.green)) lab = Label() lab.setOrigin(350, -50) lab.boxAnchor = 'ne' lab.fillColor = Color(*charts.BG_COLOR, 0.15) lab.fontSize = 72 lab.angle = 60 lab.dx = 0 lab.dy = 0 lab.setText('Wisdom Tests') draw.add(lab) return draw
def 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 exportMonthlyReport(self, file, month, year): """Outputs the monthly report to the specified file location Parameters: self: the class instance file: str - file location and name ending in .pdf month: str - required month year: int - required year """ # For conversion of month to three letter abbreviation months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] # Creating a title title = Label() title.setOrigin(300, 20) title.boxAnchor = 'ne' title.dx = 0 title.dy = -5 title.fontSize = 30 title.setText("Monthly Report") # Adding title to a drawing draw_title = Drawing(0, 40) draw_title.add(title) # Creating a subtitle subtitle = Label() subtitle.setOrigin(320, 20) subtitle.boxAnchor = 'ne' subtitle.dx = 0 subtitle.dy = -10 subtitle.fontSize = 14 # Converts month to three letter abbreviation str_month = months[int(month) - 1] # Setting the subtitle's text subtitle.setText("Australia Zoo Wildlife Hospital, " + str_month + " " + str(year)) # Adding subtitle to a drawing draw_subtitle = Drawing(0, 30) draw_subtitle.add(subtitle) # Creating a label for the first chart label_lga = Label() label_lga.setOrigin(180, 20) label_lga.boxAnchor = 'ne' label_lga.dx = 0 label_lga.dy = -20 label_lga.setText("Local Government Area Totals") # Adding label to a drawing draw_label_lga = Drawing(0, 40) draw_label_lga.add(label_lga) # Creating drawing for the lga chart draw_lga = Drawing(0, 270) draw_lga.add(self.getSpecificBarChart("LGA", month, year)) # Creating a label for the second chart label_taxons = Label() label_taxons.setOrigin(180, 20) label_taxons.boxAnchor = 'ne' label_taxons.dx = 0 label_taxons.dy = -20 label_taxons.setText("Taxon Grouping Totals") # Adding label to a drawing draw_label_taxons = Drawing(0, 40) draw_label_taxons.add(label_taxons) # Creating drawing for the taxons chart draw_taxons = Drawing(0, 270) draw_taxons.add(self.getSpecificBarChart("Taxons", month, year)) # List of drawings in order of how to place them in the canvas drawlist = [ draw_title, draw_subtitle, draw_label_lga, draw_lga, draw_label_taxons, draw_taxons ] # Creating a canvas (pdf file) and saving it to a location canvas = Canvas(file) # Creating a frame to add flowables (drawings) to frame = Frame(inch, 0, 15.92 * cm, 29.7 * cm) # Adding flowables frame.addFromList(drawlist, canvas) # Saving the pdf canvas.save()
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)) if data[1:][i][0] == 'SwapUsage' or data[1:][i][0] == 'LMK File': extraStyle.append(('BACKGROUND', (0, i + 1), (-1, i + 1), colors.lightgreen)) t.setStyle(TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica'),
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 create_bar(self, data_list, label_x_axis, contain, y_label=None, x_label=None, bar_width=520, bar_height=100, draw_width=520, draw_height=200, user_color=None, fontName="Times-Roman", fontSize=6, x_angle=0, bar_space=0): d = Drawing(width=draw_width, height=draw_height) bar = VerticalBarChart() bar.width = bar_width bar.height = bar_height bar.y = bar.height - (bar_height / 4) bar.strokeColor = colors.black bar.barLabelFormat = '%s' bar.barLabels.nudge = 7 bar.barLabels.fontSize = fontSize ################# X AXIS PROPERTIES ################# bar.categoryAxis.labels.dx = 0 bar.categoryAxis.labels.angle = x_angle bar.categoryAxis.labels.boxAnchor = 'autox' bar.categoryAxis.labels.fontSize = fontSize bar.categoryAxis.labels.fontName = self.master_font bar.categoryAxis.strokeWidth = 0.25 bar.categoryAxis.tickDown = -(bar.height) bar.categoryAxis.categoryNames = label_x_axis labX = Label() labX.boxAnchor = 'ne' labX.dx = bar.width * 2.15 labX.dy = bar.height labX.fontName = fontName labX.fontSize = fontSize labX.setText(x_label) d.add(labX) ##################################################### ################# Y AXIS PROPERTIES ################# bar.valueAxis.forceZero = 1 bar.valueAxis.labels.fontSize = fontSize bar.valueAxis.labels.fontName = fontName bar.valueAxis.rangeRound = 'both' bar.valueAxis.valueMin = 0 bar.valueAxis.visibleGrid = 1 bar.valueAxis.visibleAxis = 1 bar.valueAxis.labels.dx = -10 labY = Label() labY.boxAnchor = 'autox' labY.dy = bar.y + (bar.height / 1.5) labY.dx = bar.x - 30 labY.angle = 90 labY.fontName = fontName labY.fontSize = fontSize labY.setText(y_label) d.add(labY) ##################################################### bar.barSpacing = bar_space # bar.groupSpacing = 3 bar.data = data_list # print len(data_list) # print len(contain) if user_color != None: usage_color = user_color else: random_range = [randint(0, 100) for i in range(len(contain))] usage_color = map( lambda item: PCMYKColor(randint(0, item), randint(0, item), randint(0, item), randint(0, item)), random_range) for i in range(len(data_list)): bar.bars[i].name = contain[i].upper() bar.bars[i].fillColor = usage_color[i] legend = Legend() # legend.autoXPadding = 10 legend.alignment = 'right' legend.boxAnchor = 'sw' legend.dxTextSpace = 10 legend.fontSize = fontSize legend.fontName = fontName legend.subCols.minWidth = 55 legend.variColumn = 1 legend.deltay = 15 legend.x = bar.x legend.colorNamePairs = Auto(obj=bar) d.add(bar) d.add(legend) self.flowables.append(d)
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( """ In the drawing above, the label is defined relative to the green blob. The text box should have its north-east corner ten points down from
def balance_statistics_chart(self, control_vars, match_vars, var_names): """ Specify layout of the balance statistics chart and generate flowable object that can be added to the pdf """ drawing = Drawing() vbc = VerticalBarChart() # Chart position in document vbc.x = self.chart_offset_x vbc.y = self.chart_offset_y vbc.height = self.chart_height vbc.width = self.chart_width # Specify data # [[control_var1, control_var2], [match_var1, match_var2]] vbc.data = [control_vars, match_vars] #Set Y-Axis ranges #axis_range = self._calculate_y_axis(vbc.data) #vbc.valueAxis.valueMin = axis_range['min'] #vbc.valueAxis.valueMax = axis_range['max'] #vbc.valueAxis.valueStep = axis_range['step'] #Grid formatting vbc.valueAxis.visibleGrid = 1 vbc.valueAxis.gridStrokeColor = colors.lightgrey #Bar formatting vbc.bars[0].fillColor = colors.blue vbc.bars[1].fillColor = colors.yellow vbc.bars.strokeColor = None vbc.groupSpacing = 1 vbc.barWidth = 5 # Callout label formatting (numbers above bar) #vbc.barLabels.fontName = "Arial" vbc.barLabels.fontSize = 8 vbc.barLabels.fillColor = colors.black vbc.barLabelFormat = '%.2f' vbc.barLabels.nudge = 5 # Central axis vbc.categoryAxis.visibleTicks = 1 # X-axis labels #vbc.categoryAxis.labels.dy = -60 vbc.valueAxis.labels.fontName = 'Helvetica' vbc.categoryAxis.categoryNames = var_names lab = Label() lab.setOrigin(10, 155) lab.boxAnchor = 'ne' lab.angle = 90 lab.dx = 0 lab.dy = -15 #lab.boxStrokeColor = colors.green lab.setText('Percent Bias') drawing.add(lab) drawing.add(vbc) self.elements.append(drawing)
def results_chart(self, control_mean, match_mean, treated_mean, att): """ Specify layout of the results chart and generate flowable object that can be added to the pdf """ drawing = Drawing() vbc = VerticalBarChart() # Offset chart from border and text vbc.x = self.chart_offset_x vbc.y = self.chart_offset_y # Set figure size vbc.height = self.chart_height vbc.width = self.chart_width # Specify chart -- list of lists -- list of series with enteries vbc.data = [[control_mean, match_mean, treated_mean, att]] #Set Y-Axis ranges #axis_range = self._calculate_y_axis(vbc.data) #vbc.valueAxis.valueMin = axis_range['min'] #vbc.valueAxis.valueMax = axis_range['max'] #vbc.valueAxis.valueStep = axis_range['step'] #Grid formatting vbc.valueAxis.visibleGrid = 1 vbc.valueAxis.gridStrokeColor = colors.lightgrey # Set bar characteristics vbc.bars[(0, 0)].fillColor = colors.blue vbc.bars[(0, 1)].fillColor = colors.yellow vbc.bars[(0, 2)].fillColor = colors.red vbc.bars[(0, 3)].fillColor = colors.green vbc.bars.strokeColor = None vbc.barSpacing = 2 # Create callout labels #vbc.barLabels.fontName = "Helvetica" vbc.barLabels.fontSize = 8 vbc.barLabels.fillColor = colors.black vbc.barLabelFormat = '%.2f' vbc.barLabels.nudge = 5 # X-axis labels #vbc.categoryAxis.labels.dy = -60 #vbc.valueAxis.labels.fontName = 'Helvetica' vbc.categoryAxis.categoryNames = [ 'Control Mean', 'Matched Control Mean', 'Treatment mean', 'ATT' ] lab = Label() lab.setOrigin(10, 155) lab.boxAnchor = 'ne' lab.angle = 90 lab.dx = 0 lab.dy = -15 #lab.boxStrokeColor = colors.green lab.setText('Result Values') drawing.add(lab) drawing.add(vbc) self.elements.append(drawing)
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 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]
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(""" In the drawing above, the label is defined relative to the green blob. The text box should have its north-east corner ten points down from
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
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)) if data[1:][i][0] == 'SwapUsage' or data[1:][i][0] == 'LMK File': extraStyle.append(
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)