def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 22, 37, 45, 19, 4, 13), (20, 22, 37, 45, 19, 4, 13, 5)]): # sanity check: for d in data: if len(d)!=8: raise ValueError("bar chart data must have 8 elements "+repr(data)) drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split() catNames = [n+'-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def draw_bar_chart(pdf_text, page_height): '''Currently generates a dummy graph. Next, need to pass in data that shall be the reactors temp throughout the sequence. ''' pdf_text.showPage() drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ 'Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99' ] drawing.add(bc) renderPDF.draw(drawing, pdf_text, inch, inch) return page_height
def category_predicted_spending(c, category, h, w): """ Creates a bar graph in a PDF """ my_data = [] for i in range(1, month + 1): my_data.append(round(data.category_data(category, i, year))) budget = data.category_budget(category) re_budget = (budget - sum(my_data)) / (12 - month) for x in range(month, 12): my_data.append(re_budget) d = Drawing(0, 0) bar = VerticalBarChart() bar.x = 150 bar.y = 150 bar.data = [my_data] bar.valueAxis.valueMin = 0 bar.categoryAxis.categoryNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] bar.categoryAxis.labels.fontName = serif_font bar.valueAxis.labels.fontName = serif_font bar.categoryAxis.labels.boxAnchor = 'n' bar.categoryAxis.labels.angle = 90 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.labels.dx = -10 #below change monnth number based upon current month bar.bars[0].fillColor = PCMYKColor(150, 150, 150, 150, alpha=85) for i in range(month, 12): bar.bars[(0, i)].fillColor = PCMYKColor(0, 150, 150, 0, alpha=85) d.add(bar, '') d.drawOn(c, h, w)
def getVerticalBarChart(): data = [(3, 18, 20), (14, 12, 21)] chart = VerticalBarChart() chart.data = data chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 25 chart.valueAxis.valueStep = 5 chart.x = 5 chart.y = 5 chart.width = 240 chart.height = 100 chart.strokeColor = colors.black chart.fillColor = colors.yellow chart.groupSpacing = 0 chart.categoryAxis.categoryNames = ['A', 'B', 'C'] title = String(50, 110, 'Vertical Bar Chart', fontSize=14) drawing = Drawing(240, 120) drawing.add(title) drawing.add(chart) return drawing
def monthly_spending_bar(c, category, h, w): """ Creates a bar graph in a PDF """ my_data = [] for i in range(1, 12 + 1): my_data.append(data.category_data(category.lower(), i, year)) for i in range(month, 12): my_data[i] = 0 #d = Drawing(300, 250) d = Drawing(0, 0) bar = VerticalBarChart() bar.x = 150 bar.y = 150 bar.data = [my_data] bar.valueAxis.valueMin = 0 bar.categoryAxis.categoryNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] bar.categoryAxis.labels.fontName = serif_font bar.valueAxis.labels.fontName = serif_font bar.categoryAxis.labels.boxAnchor = 'n' bar.categoryAxis.labels.angle = 90 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.labels.dx = -10 #below change monnth number based upon current month bar.bars[0].fillColor = PCMYKColor(150, 150, 150, 150, alpha=85) bar.bars[(0, month - 1)].fillColor = PCMYKColor(150, 0, 0, 0, alpha=85) d.add(bar, '') d.drawOn(c, 200, 480)
def persona(request,id): if 'pdf' in request.GET: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="persona_%s.pdf"'%id p=canvas.Canvas(response) drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4),(14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing,p,100,480) p.showPage() p.save() return response else: return HttpResponse("la informacion de la persona %s" %id)
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 gen_bar_graphs(comparison_values, location, emission): bc = VerticalBarChart() labels = [] data = [] comparison_values.append([location, emission]) comparison_values.sort(key=lambda x: x[1]) for pair in comparison_values: labels.append(pair[0]) data.append(pair[1]) data = [data] location_index = labels.index(location) bc.x = -150 bc.y = -110 bc.height = 100 bc.width = 150 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = data[0][-1] + data[0][-1] * .1 #bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = labels for i in range(len(labels)): bc.bars[(0, i)].fillColor = colors.Color(166.0 / 255, 189.0 / 255, 219.0 / 255) bc.bars[(0, location_index)].fillColor = colors.Color(28.0 / 255, 144.0 / 255, 153.0 / 255) return bc
def getdrawing(): from reportlab.graphics.shapes import Drawing from reportlab.lib import colors from reportlab.graphics.charts.barcharts import VerticalBarChart drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = "ne" bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ "Jan-99", "Feb-99", "Mar-99", "Apr-99", "May-99", "Jun-99", "Jul-99", "Aug-99" ] drawing.add(bc) return drawing
def recommend(self, howMany): userKnownLanguages = {} for button in self.buttons: if(button.clicked == True): if button.t not in userKnownLanguages: userKnownLanguages[button.t] = 1 topicOfChoice = "" # Grab the topic the user selected try: index = self.listbox.curselection()[0] topicOfChoice = self.listbox.get(index) except IndexError: pass nearestCluster = classifier.nearest(userKnownLanguages, self.indexByTopic) for frame in self.frames: frame.pack_forget() self.displayRecommendations(topicOfChoice, userKnownLanguages) data = classifier.difference(self.indexByTopic[nearestCluster]['languages'], userKnownLanguages) labels,d1 =zip(*data) d = Drawing(300,200) chart = VerticalBarChart() chart.width = 260 chart.height = 160 chart.x = 20 chart.y = 10 chart.data = [d1] chart.categoryAxis.categoryNames = labels d.add(chart) d.save(formats=['pdf'],outDir='.',fnRoot='graph') os.system('open graph.pdf')
def gen_bar_graphs(comparison_values, location, emission): bc = VerticalBarChart() labels = [] data = [] comparison_values.append([location, emission]) comparison_values.sort(key = lambda x: x[1]) for pair in comparison_values: labels.append(pair[0]) data.append(pair[1]) data = [data] location_index = labels.index(location) bc.x = -150 bc.y = -110 bc.height = 100 bc.width = 150 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = data[0][-1] + data[0][-1] * .1 distance = abs(int(math.log10(abs(data[0][-1])))) + 1 # distance of 1 significant figure to decimal point bc.valueAxis.valueStep = float(format(data[0][-1], '.1g')) / 3 bc.valueAxis.labelTextFormat = '%0.' + str(distance) + 'g' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = labels for i in range(len(labels)): bc.bars[(0, i)].fillColor = colors.Color(166.0/255, 189.0/255, 219.0/255) bc.bars[(0, location_index)].fillColor = colors.Color(28.0/255, 144.0/255, 153.0/255) return bc
def simple_stacked_bar_chart(): """ Creates a bar chart in a PDF """ d = Drawing(280, 250) bar = VerticalBarChart() bar.x = 50 bar.y = 85 data = [[1, 2, 3, None, None, None, 5], [10, 5, 2, 6, 8, 3, 5] ] bar.data = data bar.categoryAxis.categoryNames = ['Year1', 'Year2', 'Year3', 'Year4', 'Year5', 'Year6', 'Year7'] bar.bars[0].fillColor = colors.green bar.bars[1].fillColor = colors.blue bar.categoryAxis.labels.angle = 45 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.style = 'stacked' d.add(bar, '') doc = SimpleDocTemplate('17.simple_stacked_bar_chart.pdf') story = [] story.append(d) doc.build(story)
def simple_bar_chart_angled_labels(): d = Drawing(280, 250) bar = VerticalBarChart() bar.x = 50 bar.y = 85 data = [ [1, 2, 3, None, None, None, 5], [10, 5, 2, 6, 8, 3, 5], [5, 7, 2, 8, 8, 2, 5], [2, 10, 2, 1, 8, 9, 5], ] bar.data = data bar.categoryAxis.categoryNames = [ 'Year1', 'Year2', 'Year3', 'Year4', 'Year5', 'Year6', 'Year7' ] bar.bars[0].fillColor = colors.green bar.bars[1].fillColor = colors.blue bar.bars[2].fillColor = colors.red bar.bars[3].fillColor = colors.purple bar.categoryAxis.labels.angle = 45 bar.categoryAxis.labels.dy = -15 bar.groupSpacing = 12 bar.barSpacing = 2 d.add(bar, '') doc = SimpleDocTemplate('simple_bar_chart_angled_labels.pdf') story = [] story.append(d) doc.build(story)
def myBarChart(data): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 catNames = ('Trial1 Trial2 Trial3 Trial4 Trial5').split() bc.categoryAxis.categoryNames = catNames bc.bars[0].fillColor = colors.red bc.bars[1].fillColor = colors.lightblue drawing.add(bc) return drawing
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') catNames = map(lambda n:n+'-99', catNames) bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def ventas_totales(pos, periodos, ventas_totales): arreglo = [periodos, ventas_totales] table = Table(arreglo, colWidths=3 * cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT')]) for index, row in enumerate(arreglo): bg_color = colors.red ini, fin = (0, index), (len(row) - 1, index) table.setStyle([("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', ini, fin, bg_color)]) story.append(table) d = Drawing(400, 200) data = [(11541548, 15618561, 56416646)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60000000 bc.valueAxis.valueStep = 10000000 #paso de distancia entre punto y punto bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = ['2017', '2018', '2019'] bc.groupSpacing = 10 bc.barSpacing = 2 #bc.categoryAxis.style = 'stacked' # Una variación del gráfico d.add(bc) #pprint.pprint(bc.getProperties()) story.append(d)
def create_chart(self, data, y_label, d_format, cols): """Generates and returns a bar chart object""" chart = VerticalBarChart() # Create a bar chart chart.width = self.W - (self.MARGIN * 2) # Set chart width chart.height = self.H / 2 # Set chart height chart.x = self.MARGIN # Shift right to centre chart.y = (self.H / 2) - self.MARGIN # Shift up to near top chart.valueAxis.valueMin = 0 # Baseline of axes (set to 0) # Set bar colors for i in range(len(data)): chart.bars[i].fillColor = cols[i] # Add data to chart formatted_data = [] for data_item in data: formatted_data.append([data_item]) chart.data = formatted_data # Add labels to chart chart.categoryAxis.categoryNames = [y_label] chart.barLabelFormat = d_format # Format of text to display on labels chart.barLabels.nudge = 8 # Nudge labels upwards by 8px return chart
def draw_bar_chart(pdf_text, page_height): '''Currently generates a dummy graph. Next, need to pass in data that shall be the reactors temp throughout the sequence. ''' pdf_text.showPage() drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing, pdf_text, inch, inch) return page_height
def make_drawing(d, answerKey): drawing = Drawing(400, 200) maxData = 0 for count in d: if count > maxData: maxData = count data = [ tuple(d), ] names = answerKey bc = VerticalBarChart() bc.x = 20 bc.y = 50 bc.height = 180 bc.width = 400 bc.data = data bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = maxData bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = -10 bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.categoryNames = names drawing.add(bc) return drawing
def createpdf(self, datas): drawing = Drawing(400, 200) # data = [(13, 5, 20),(14, 6, 21)] data = datas bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99'] # bc.categoryAxis.categoryNames = ytype drawing.add(bc) drawing.add(String(250, 150, "ss", fontSize=14, fillColor=colors.red)) # drawing.add(String(250,150,des, fontSize=14,fillColor=colors.red)) renderPDF.drawToFile(drawing, 'report1.pdf', 'API')
def conversion_chart(data, labels): """Create chart that can be drawn as a gif with given data/labels""" drawing = Drawing(500, 400) bc = VerticalBarChart() bc.x = 80 bc.y = 80 bc.height = 290 bc.width = 390 bc.data = data bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.valueAxis.labelTextFormat = '%2.2f' bc.barLabels.fontSize = 15 bc.barLabelFormat = '%2.2f' bc.barLabels.boxAnchor = 's' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = 2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = labels drawing.add(bc) return drawing
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split( ' ') catNames = [n+'-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def draw_bar(bar_data=[], ax=[], items=[]): drawing = Drawing(500, 250) bc = VerticalBarChart() bc.x = 35 bc.y = 100 bc.height = 120 bc.width = 350 bc.data = bar_data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 20 bc.categoryAxis.categoryNames = ax # 图示 leg = Legend() leg.fontName = 'song' leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 465 leg.y = 220 leg.dxTextSpace = 10 leg.columnMaximum = 3 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing
def show_figure(data, y_max, x_category, legend_category): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 150 bc.width = 450 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = y_max # bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = len(data[0]) # bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = x_category drawing.add(bc) # add legend from here swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 190 swatches.deltax = 30 swatches.dxTextSpace = 10 swatches.columnMaximum = 1 color_list = (colors.red, colors.green, colors.blue, colors.pink, colors.yellow) items = [] for index, item in enumerate(legend_category): items.append((color_list[index], item)) swatches.colorNamePairs = items drawing.add(swatches, 'legend') return drawing
def getBarChart(self, x_values, y_values): """Gets a bar chart with the given values Parameters: self: the class instance x_values: list - x values for the bar chart y_values: list - y values for the bar chart Returns: reportlab Vertical Bar Chart - bar chart with inputted values """ y_values = [tuple(y_values)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = y_values bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 250 bc.valueAxis.valueStep = 25 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 45 bc.categoryAxis.categoryNames = x_values return bc
def overview_year_spend_by_month(c, w, h): my_data = data.monthly_total(year) total_budget = data.budget() left_budget = (total_budget - sum(my_data)) / (12 - month) for i in range(month, 12): my_data[i] = left_budget d = Drawing(0, 0) bar = VerticalBarChart() bar.x = 150 bar.y = 150 bar.data = [my_data] bar.valueAxis.valueMin = 0 bar.categoryAxis.categoryNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] bar.categoryAxis.labels.fontName = serif_font bar.valueAxis.labels.fontName = serif_font bar.categoryAxis.labels.boxAnchor = 'n' bar.categoryAxis.labels.angle = 90 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.labels.dx = -10 bar.bars[0].fillColor = PCMYKColor(150, 150, 150, 150, alpha=85) bar.bars[(0, month - 1)].fillColor = PCMYKColor(150, 0, 0, 0, alpha=85) for i in range(month, 13): bar.bars[(0, i)].fillColor = PCMYKColor(0, 150, 150, 0, alpha=85) d.add(bar, '') d.drawOn(c, w, h)
def create_bar_graph(): """ Creates a bar graph in a PDF """ d = Drawing(280, 250) bar = VerticalBarChart() bar.x = 50 bar.y = 85 data = [[1, 2, 3, None, None, None, 5], [10, 5, 2, 6, 8, 3, 5], [5, 7, 2, 8, 8, 2, 5], [2, 10, 2, 1, 8, 9, 5], ] bar.data = data bar.categoryAxis.categoryNames = ['Year1', 'Year2', 'Year3', 'Year4', 'Year5', 'Year6', 'Year7'] bar.bars[0].fillColor = PCMYKColor(0, 100, 100, 40, alpha=85) bar.bars[1].fillColor = PCMYKColor(23, 51, 0, 4, alpha=85) bar.bars.fillColor = PCMYKColor(100, 0, 90, 50, alpha=85) d.add(bar, '') d.save(formats=['pdf'], outDir='.', fnRoot='test')
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.labels.fontName = fontName bc.barLabels.fontName = fontName bc.barLabelFormat = u'\xc5%s' catNames = u'J\xe4n Feb M\xe4r \xc4pr M\xe4y J\xfcn J\xfcl \xc4\xfcg'.split( ' ') bc.barLabelArray = catNames catNames = [n + '-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def createBarGraph(self): """ Creates a bar graph in a PDF """ d = Drawing(300, 250) bar = VerticalBarChart() bar.x = 90 bar.y = 130 BarData = [] CategoryLabels = [] result_data = getStudentTrendInExams(self.student['user_id']) for rd in result_data: BarData.append(float(rd['points'])) CategoryLabels.append(rd['label']) bar.data = [BarData] bar.categoryAxis.categoryNames = CategoryLabels bar.valueAxis.valueMin = 0 bar.valueAxis.valueMax = 100 bar.valueAxis.valueStep = 20 bar.categoryAxis.labels.dx = -18 bar.categoryAxis.labels.dy = -30 bar.categoryAxis.labels.angle = 60 bar.bars[0].fillColor = colors.black d.add(bar, '') return d
def createReadsHistogram(self): ''' Routine to create histogram of numbers of 'reads' for given years ''' # The vertical bar chart will get added to the 'drawing' object drawing = Drawing(400, 200) # Now we can start constructing the vertical bar chart lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 # Record the years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['reads histogram'].keys()))) # This list will hold the data points for the histogram lc.data = [] # Record the counts of both reads of refereed and non-refereed papers refereed = [] non_refereed = [] # The maximum number of reads will be used to scale the y axis max_reads = 0 # Take only the first two values of each value string in the histogram data # The first is for 'all' papers, the second for the 'refereed' papers for year in years: values = map(lambda a: int(a),self.data['reads histogram'][str(year)].split(':')[:2]) max_reads = max(max_reads,max(values)) refereed.append(values[1]) non_refereed.append(values[0]-values[1]) lc.data.append(refereed) lc.data.append(non_refereed) # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lc.categoryAxis.labels.dx = -6 lc.categoryAxis.labels.dy = -6 # and rotate the labels by 90 degrees lc.categoryAxis.labels.angle = 90 # Define the value step and maximum for the y axis lc.valueAxis.valueMax = int(math.ceil(float(max_reads)/10.0))*10 lc.valueAxis.valueStep = max(int(math.floor(float(max_reads)/10.0)),1) lc.valueAxis.valueMin = 0 # The label names are the access years lc.categoryAxis.categoryNames = map(lambda a: str(a), years) # Now add the histogram to the 'drawing' object drawing.add(lc) # Add a legend to the histogram so that we now which color means what legend = Legend() legend.alignment = 'right' legend.x = 380 legend.y = 160 legend.deltax = 60 legend.dxTextSpace = 10 items = [(colors.red, 'refereed'), (colors.green, 'non-refereed')] legend.colorNamePairs = items drawing.add(legend, 'legend') # Finally add a title to the histogram drawing.add(String(200,190,"reads histogram", textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
def testWidget(self): from reportlab.graphics.charts.barcharts import VerticalBarChart vbc = VerticalBarChart() vbc.x = 50 vbc.y = 50 from reportlab.graphics.widgetbase import Sizer siz = Sizer() siz.add(vbc, 'vbc') assert siz.getBounds()[0:2] <> (0,0)
def testWidget(self): from reportlab.graphics.charts.barcharts import VerticalBarChart vbc = VerticalBarChart() vbc.x = 50 vbc.y = 50 from reportlab.graphics.widgetbase import Sizer siz = Sizer() siz.add(vbc, 'vbc') assert siz.getBounds()[0:2] != (0, 0)
def pie_chart(data_for_pie): d = Drawing(400, 400) pc = Pie() pc.x = 100 pc.y = 210 pc.width = 170 pc.height = 170 pc.sideLabels = True pc.sideLabelsOffset = 0.05 car_name_lst = [] car_sales_lst = [] car_price_lst = [] data_for_pie = data_for_pie[1:] data_for_pie = sorted(data_for_pie, key=itemgetter(3), reverse=True) # so i can show 10 most popular cars for i in data_for_pie: car_name = i[1] car_name_lst.append(car_name) car_sales = i[3] car_sales_lst.append(car_sales) car_price = float(i[2].strip( "$")) #by default all the prices are in '', for example '18731.76' car_price_lst.append(car_price) pc.data = car_sales_lst[:10] pc.labels = list(set( car_name_lst[:10])) # by using set i wont have similar items in list d.add(pc, '') """have to done this because in task i have to calculate revenue on Xaxis and car name on Yaxis""" revenue_calculation_1 = car_sales_lst[:10] revenue_calculation_2 = car_price_lst[:10] car_revenue_list = [] for i in range(len(car_price_lst[:10])): reven = revenue_calculation_1[i] * revenue_calculation_2[i] car_revenue_list.append( int(reven)) #using int because its many digits after "," """bar chart """ data = [tuple(car_revenue_list) ] #for some reason bar chart accepts only [[]] or [()] bc = VerticalBarChart() bc.x = 50 bc.y = 0 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 7000000 bc.valueAxis.valueMax = 23000000 bc.valueAxis.valueStep = 1000000 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = list(set(car_name_lst[:10])) d.add(bc) return d
def draw_bar_chart(charmin, charmax, x_list, data=[()], x_label_angle=0, bar_color=colors.HexColor("#7BB8E7"), height=125, width=220): ''' :param min: 设置y轴的最小值 :param max: 设置y轴的最大值 :param x_list: x轴上的标签 :param data: y轴对应标签的值 :param x_label_angle: x轴上标签的倾斜角度 :param bar_color: 柱的颜色 可以是含有多种颜色的列表 :param height: 柱状图的高度 :param width: 柱状图的宽度 :return: ''' bc = VerticalBarChart() bc.x = 50 # x和y是柱状图在框中的坐标 bc.y = 50 bc.height = height # 柱状图的高度 bc.width = width # 柱状图的宽度 bc.data = data for j in range(0, len(x_list)): setattr(bc.bars[j], 'fillColor', bar_color) # bar_color若含有多种颜色在这里分配bar_color[j] # 调整step minv = charmin * 0.5 maxv = charmax * 1.5 maxAxis = int(height / 10) # 向上取整 minStep = int((maxv - minv + maxAxis - 1) / maxAxis) bc.valueAxis.valueMin = charmin * 0.5 #设置y轴的最小值 bc.valueAxis.valueMax = charmax * 1.5 #设置y轴的最大值 bc.valueAxis.valueStep = (charmax - charmin) / 4 #设置y轴的最小度量单位 if bc.valueAxis.valueStep < minStep: bc.valueAxis.valueStep = minStep if bc.valueAxis.valueStep == 0: bc.valueAxis.valueStep = 1 bc.categoryAxis.labels.boxAnchor = 'ne' # x轴下方标签坐标的开口方向 bc.categoryAxis.labels.dx = -5 # x和y是x轴下方的标签距离x轴远近的坐标 bc.categoryAxis.labels.dy = -5 bc.categoryAxis.labels.angle = x_label_angle # x轴上描述文字的倾斜角度 # bc.categoryAxis.labels.fontName = 'song' x_real_list = [] if len(x_list) > 10: for i in range(len(x_list)): tmp = '' if i % 5 != 0 else x_list[i] x_real_list.append(tmp) else: x_real_list = x_list bc.categoryAxis.categoryNames = x_real_list return bc
def xerar_barChart_serv(self): """ Xera un gráfico de barras co número de empregados por departamento nos últimos 8 meses a partir da base de datos :return: """ from reportlab.graphics.charts.barcharts import VerticalBarChart styles = getSampleStyleSheet() ptext = Paragraph( 'Número de empregados por departamento nos últimos 8 meses:', styles['Heading1']) self.story.append(ptext) d = Drawing(400, 200) p = self.cursor.execute( """SELECT (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'produccion')) AS prod, (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'finanzas')) AS finanzas, (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'informatica')) AS informatica, (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'publicidade')) FROM servizos AS publicidade """).fetchone() self.conn.text_factory = str data = [(25, 34, 14, 18, 36, 22, 19, p[0]), (26, 31, 22, 24, 16, 10, 18, p[1]), (34, 40, 18, 9, 25, 7, 2, p[2]), (29, 20, 19, 16, 34, 40, 15, p[3])] bc = VerticalBarChart() bc.x = 50 bc.y = 55 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 # paso de distancia entre punto y punto bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ 'Xan-19', 'Feb-19', 'Mar-19', 'Abr-19', 'Mai-19', 'Xuñ-19', 'Xul-19', 'Ago-19' ] bc.groupSpacing = 10 bc.barSpacing = 2 # bc.categoryAxis.style = 'stacked' # Una variación del gráfico d.add(bc) self.story.append(d)
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)): datapickle = open(os.path.join(pickledir, versionpickle), 'rb') data = cPickle.load(datapickle) datapickle.close() ## calculate the possible widths and heights of chart, bars, labels and so on maxversionstring = max(map(lambda x: len(x[0]), data)) barwidth = 15 chartwidth = len(data) * barwidth + 10 * len(data) maxvalue = max(map(lambda x: x[1], data)) step = int(math.log(maxvalue, 10)) valueStep = pow(10, step) ## calculate a possible good value for startx and starty so labels are not cut off startx = max(10 + step * 10, 30) ## TODO: fiddle with values to create nicer looking graphs starty = maxversionstring * 10 + 20 drawheight = 225 + starty drawwidth = chartwidth + startx + 10 ## create the drawing drawing = Drawing(drawwidth, drawheight) bc = VerticalBarChart() bc.x = startx bc.y = starty bc.height = 200 bc.width = chartwidth bc.data = [tuple(map(lambda x: x[1], data))] bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.labels.fontSize = 16 bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = valueStep bc.categoryAxis.labels.boxAnchor = 'w' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = -90 bc.categoryAxis.labels.fontSize = 16 bc.categoryAxis.categoryNames = map(lambda x: x[0], data) bc.barWidth = barwidth drawing.add(bc) outname = os.path.join(imagedir, picklehash) renderPM.drawToFile(drawing, outname, fmt='PNG') return picklehash
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)): datapickle = open(os.path.join(pickledir, versionpickle), 'rb') data = cPickle.load(datapickle) datapickle.close() ## calculate the possible widths and heights of chart, bars, labels and so on maxversionstring = max(map(lambda x: len(x[0]), data)) barwidth = 15 chartwidth = len(data) * barwidth + 10 * len(data) maxvalue = max(map(lambda x: x[1], data)) step = int(math.log(maxvalue,10)) valueStep = pow(10,step) ## calculate a possible good value for startx and starty so labels are not cut off startx = max(10 + step * 10, 30) ## TODO: fiddle with values to create nicer looking graphs starty = maxversionstring * 10 + 20 drawheight = 225 + starty drawwidth = chartwidth + startx + 10 ## create the drawing drawing = Drawing(drawwidth, drawheight) bc = VerticalBarChart() bc.x = startx bc.y = starty bc.height = 200 bc.width = chartwidth bc.data = [tuple(map(lambda x: x[1], data))] bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.labels.fontSize = 16 bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = valueStep bc.categoryAxis.labels.boxAnchor = 'w' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = -90 bc.categoryAxis.labels.fontSize = 16 bc.categoryAxis.categoryNames = map(lambda x: x[0], data) bc.barWidth = barwidth drawing.add(bc) outname = os.path.join(imagedir, picklehash) renderPM.drawToFile(drawing, outname, fmt='PNG') return picklehash
def run(self, include_sub_survey=False, dimensions=[]): # Build data set averages = [] category_names = [] for dimension in self.getDimensions(): averages.append(self.get_average_score_for_dimension( include_sub_survey=include_sub_survey, dimension=dimension)) category_names.append(dimension) drawing = Drawing(600, 300) bc = VerticalBarChart() bc.x = 20 bc.y = 20 bc.height = 260 bc.width = 580 bc.data = [averages] bc.categoryAxis.categoryNames = category_names bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 10 bc.categoryAxis.labels.textAnchor = 'middle' bc.categoryAxis.visibleTicks = 0 bc.valueAxis.valueMax = 100.0 bc.valueAxis.valueMin = min(averages, 0) bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.labels.textAnchor = 'middle' bc.barLabelFormat = '%.0f' bc.barLabels.dy = 8 bc.barLabels.fontName = 'Helvetica' bc.barLabels.fontSize = 10 bc.barWidth = len(averages) bc.fillColor = None drawing.add(bc) # Write out data = drawing.asString('png') request = self.REQUEST response = request.RESPONSE response.setHeader('Content-Type', 'image/png') response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId()) response.setHeader('Content-Length', len(data)) response.setHeader('Cache-Control', 's-maxage=0') return data
def chartBins(bins, filename): data = [] labels = [] keys = bins.keys() keys.sort() for k in keys: mid = (k[1] + k[0]) / 2.0 labels.append(str(mid)) data.append(len(bins[k])) maxval = max(data) data = [tuple(data)] # now, make the chart bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 500 bc.width = 1100 bc.data = data bc.valueAxis.valueMin = 0 bc.valueAxis.valueStep = 10 bc.valueAxis.valueMax = maxval + bc.valueAxis.valueStep bc.categoryAxis.labels.boxAnchor = "n" # bc.categoryAxis.labels.dx = 8 # bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 30 new_labels = [] for i, l in enumerate(labels): if i % 5 == 0: new_labels.append(l) else: new_labels.append("") # bc.categoryAxis.categoryNames = labels bc.categoryAxis.categoryNames = new_labels drawing = Drawing(1200, 600) drawing.add(bc) from reportlab.graphics import renderPM renderPM.drawToFile(drawing, output_filename)
def graphout(statenames, data): drawing = Drawing(500, 200) lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 450 lc.data = data statenames = statenames lc.categoryAxis.categoryNames = statenames lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.labels.angle = 270 lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 10000000 #1500 lc.valueAxis.valueStep = 1000000 #300 drawing.add(lc) return drawing
def test_21_barCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.barcharts import VerticalBarChart pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) d = Drawing(400,200) data = [ (13,5,20,22,37,45,19,4), (14,6,21,23,38,46,20,5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.groupSpacing = 10 bc.barSpacing = 2.5 bc.valueAxis._valueMin = 0 bc.valueAxis._valueMax = 50 bc.valueAxis._valueStep = 10 bc.categoryAxis.categoryNames = ['1','2','3','4','5','6','7','8'] # bc.categoryAxis.style = 'stacked' d.add(bc) elements.append(d) doc.build(elements)
def draw(self, cur_drawing, start_x, start_y, end_x, end_y): """Draw a bar chart with the info in the specified range.""" bar_chart = VerticalBarChart() if self.chart_title: self._draw_title(cur_drawing, self.chart_title, start_x, start_y, end_x, end_y) # set the position of the bar chart x_start, x_end, y_start, y_end = self._determine_position(start_x, start_y, end_x, end_y) bar_chart.x = x_start bar_chart.y = y_start bar_chart.width = abs(x_start - x_end) bar_chart.height = abs(y_start - y_end) # set the information in the bar chart bar_chart.data = self.display_info bar_chart.valueAxis.valueMin = min(self.display_info[0]) bar_chart.valueAxis.valueMax = max(self.display_info[0]) for data_set in self.display_info[1:]: if min(data_set) < bar_chart.valueAxis.valueMin: bar_chart.valueAxis.valueMin = min(data_set) if max(data_set) > bar_chart.valueAxis.valueMax: bar_chart.valueAxis.valueMax = max(data_set) # set other formatting options if len(self.display_info) == 1: bar_chart.groupSpacing = 0 style = TypedPropertyCollection(BarChartProperties) style.strokeWidth = 0 style.strokeColor = colors.green style[0].fillColor = colors.green bar_chart.bars = style # set the labels # XXX labels don't work yet # bar_chart.valueAxis.title = self.x_axis_title # bar_chart.categoryAxis.title = self.y_axis_title cur_drawing.add(bar_chart)
def create_barchart(barchart_data): color=[green,red,blue,yellow,black] data_length=len(barchart_data["data"]) bar_chart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = barchart_data["data"] bc.fillColor=lightblue bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = list(barchart_data["label"][0]) for i in xrange(data_length): bc.bars[i].fillColor = color[i] bar_chart.add(bc) ###legend#### bar_leg = LineLegend() bar_leg.boxAnchor = 'sw' bar_leg.x = 100 bar_leg.y = -1 bar_leg.columnMaximum = 1 bar_leg.yGap = 0 bar_leg.deltax = 50 bar_leg.deltay = 0 bar_leg.dx = 10 bar_leg.dy = 1.5 bar_leg.fontSize = 10 bar_leg.alignment = 'right' bar_leg.dxTextSpace = 5 bar_leg.colorNamePairs = [(color[i],barchart_data["legend"][0][i]) for i in xrange(data_length)] bar_chart.add(bar_leg) return bar_chart
def getPDF(values=[]): d = Drawing(1700, 900) # image size chart = VerticalBarChart() chart.width = 1600 chart.height = 800 chart.x = 110 chart.y = 90 chart.data = [values] chart.groupSpacing = 10 chart.categoryAxis.labels.angle = 45 chart.valueAxis.labels.fontSize = 18 chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = getMaxValue(values) chart.categoryAxis.labels.fontSize = 24 chart.categoryAxis.categoryNames = n_store[1 : len(n_store)] chart.valueAxis.valueMin = 0 d.add(chart) d.save(fnRoot="test", formats=["pdf"])
def graphout(prod_catnames, data): drawing = Drawing(500, 200) lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 450 lc.data = data #prod_catnames = prod_catnames lc.categoryAxis.categoryNames = prod_catnames lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.labels.angle = 270 lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 5000 #1500 lc.valueAxis.valueStep = 1000 #300 #lc.lines[0].strokeWidth = 2 #lc.lines[0].symbol = makeMarker('FilledCircle') # added to make filled circles. #lc.lines[1].strokeWidth = 1.5 drawing.add(lc) return drawing
def verticalbargraph(data, elements): drawing = Drawing(0, 200) # for indices bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch))
def letrasGrafico(data): "Make a slightly pathologic bar chart with only TWO data items." drawing = Drawing(800, 300) bc = VerticalBarChart() bc.x = 50 bc.y = -10 bc.height = 300 bc.width = 300 bc.barWidth = 15 bc.Title = "Frencuencias en " bc.data = data #bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 7000 bc.valueAxis.valueStep = 500 bc.categoryAxis.labels.boxAnchor = 'e' bc.categoryAxis.labels.angle = 0 abc = "abcdefghijklmnopqrstuvwxyz" bc.categoryAxis.categoryNames = list(abc) drawing.add(bc) return drawing
def vertical_bar_graph(data, elements): drawing = Drawing(0, 200) # for indices bc = VerticalBarChart() bc.x =15 # x,y define the left bottom of graph bc.y = -130 bc.height = 250 bc.width = 500 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Ques1', 'Ques2', 'Ques3', 'Ques4', 'Ques5', 'Ques6', 'Ques7', 'Ques8'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch))
def myBarChart(data): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.barWidth = .3*inch bc.groupSpacing = .2 * inch bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 catNames = string.split('Trial1 Trial2 Trial3 Trial4 Trial5') bc.categoryAxis.categoryNames = catNames bc.bars[0].fillColor = colors.blue bc.bars[1].fillColor = colors.lightblue drawing.add(bc) return drawing
def getChart(self): d = Drawing(300, 200) chart = VerticalBarChart() chart.width = 560 chart.height = 460 chart.x = 50 chart.y = 50 chart.height = 125 chart.width = 300 chart.strokeColor = colors.black chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 100 chart.valueAxis.valueStep = 10 chart.categoryAxis.labels.boxAnchor = 'ne' chart.categoryAxis.labels.dx = 8 chart.categoryAxis.labels.dy = -2 chart.categoryAxis.labels.angle = 0 chart.data = self.marks#self.averages chart.categoryAxis.categoryNames = self.chartXValues#self.studentNumbers d.add(chart) #d.save(fnRoot='test', formats=['png', 'pdf']) return d
def __init__(self, width, height, labels, data): IRender.__init__(self, width, height, labels, data) #self.w = self.width #self.h = self.height #data = [[int(line[1])] for line in self.data] #labels = [line[0] for line in self.data] #plot = cairoplot.VerticalBarPlot('/tmp/tmp.png', data, self.w*2, self.h*2, x_labels=labels, grid=True, display_values=True) ##plot.font_size *= 2 #plot.render() #plot.commit() #with open('/tmp/tmp.png') as f: # self.image = Image(StringIO(f.read()), self.w, self.h) bc = VerticalBarChart() bc.x = 40 bc.y = 50 bc.height = self.height - 60 bc.width = self.width - 60 bc.data = [[int(line[1]) for line in self.data]] bc.strokeColor = colors.white bc.bars.strokeColor = RED bc.bars.fillColor = RED bc.bars[0].fillColor = RED bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = max([int(line[1]) for line in self.data]) bc.valueAxis.valueStep = bc.valueAxis.valueMax/10 if not bc.valueAxis.valueStep: bc.valueAxis.valueStep = 1 bc.valueAxis.valueMax = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [line[0] for line in self.data] self.drawing = Drawing(self.width, self.height) self.drawing.add(bc)
def generate_certificate(elements): style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.red), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red), ('BOX', (0, 0), (-1, -1), 0.50, colors.green), ('BACKGROUND', (0, 0), (-1, -1), colors.blue), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = "RGB" styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) return elements
def createCitationHistogram(self): ''' Routine to create a histogram of citations: 1. refereed papers to refereed papers 2. refereed papers to non-refereed papers 3. non-refereed papers to refereed papers 4. non-refereed papers to non-refereed papers (where 'to X' means 'to the papers of type X in the publication set, used to generate the metrics) ''' # The vertical bar chart will get added to the 'drawing' object drawing = Drawing(400, 200) # Now we can start constructing the vertical bar chart lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 # Record the publication years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['citation histogram'].keys()))) # This list will hold the data points for the histogram lc.data = [] # Record the counts for the 4 different types of citations ref_ref = [] ref_non = [] non_ref = [] non_non = [] # The maximum number of citations will be used to scale the y axis max_citations = 0 # Take only the first four values of each value string in the histogram data for year in years: values = map(lambda a: int(a),self.data['citation histogram'][str(year)].split(':')[:4]) all2all = values[0] all2ref = values[2] ref2ref = values[3] ref2all = values[1] all2non = all2all - all2ref ref2non = ref2all - ref2ref non2all = all2all - ref2all non2ref = all2ref - ref2ref non2non = non2all - non2ref ref_ref.append(ref2ref) ref_non.append(ref2non) non_ref.append(non2ref) non_non.append(non2non) max_citations = max(max_citations,ref2ref,ref2non,non2ref,non2non) lc.data.append(ref_ref) lc.data.append(ref_non) lc.data.append(non_ref) lc.data.append(non_non) # If there are no citations, just omit this histogram: if max_citations == 0: return # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lc.categoryAxis.labels.dx = -6 lc.categoryAxis.labels.dy = -6 # and rotate the labels by 90 degrees lc.categoryAxis.labels.angle = 90 # The label names are the publication years lc.categoryAxis.categoryNames = map(lambda a: str(a), years) # Define the colors for the various bars lc.bars[0].fillColor = colors.red lc.bars[1].fillColor = colors.green lc.bars[2].fillColor = colors.blue lc.bars[3].fillColor = colors.orange # Define the value step and maximum for the y axis lc.valueAxis.valueMax = int(math.ceil(float(max_citations)/10.0))*10 lc.valueAxis.valueStep = max(int(math.floor(float(max_citations)/10.0)),1) # Now add the histogram to the 'drawing' object drawing.add(lc) # Add a legend to the histogram so that we now which color means what legend = Legend() legend.alignment = 'right' legend.x = 380 legend.y = 160 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 6 items = [(colors.red, 'refereed to refereed'), (colors.green, 'refereed to non-refereed'),(colors.blue, 'non-refereed to refereed'),(colors.orange, 'non-refereed to non-refereed')] legend.colorNamePairs = items drawing.add(legend, 'legend') # Finally add a title to the histogram drawing.add(String(200,190,"citation histogram", textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
time = float(f.read()) data[algorithm][graph]['time_gpu'] = time for algo in data: speedup = [[]] graphs = [] for graph in data[algo]: cpu_time = data[algo][graph]['time_cpu'] gpu_time = data[algo][graph]['time_gpu'] speedup[0].append(cpu_time / gpu_time) graphs.append(graph) drawing = Drawing(400, 300) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 200 bc.width = 300 bc.data = speedup bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = max(speedup[0]) + 1 bc.valueAxis.valueStep = max(1, int(floor(max(speedup[0]) / 5.))) bc.valueAxis.tickRight = 300 bc.valueAxis.strokeDashArray = [2, 2] bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2
def _rawDraw(self, x, y): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics.widgets.markers import makeMarker self._setScale([self.dataBar]) (x1, y1, Width, Height) = self._getGraphRegion(x, y) #self._drawBox(x1, y1, Width, Height) #Build the graph self.drawing = Drawing(self.width, self.height) #Size of the Axis SizeXaxis = 14 SizeYaxis = 0.0 countSteps = int(self.valueMax / self.valueStep) for n in range(countSteps + 1): eachValue = self.valueMin + n * self.valueStep SizeYaxis = max(SizeYaxis, self._stringWidth(self._customSecondsLabelFormat(eachValue), 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: bc.data = self.dataBar bc.categoryAxis.categoryNames = self.dataNames if len(self.dataNames) < 16: bc.barLabelFormat = self._customSecondsLabelFormat bc.barLabels.dy = 0.08*inch bc.barLabels.fontSize = 9 else: bc.data = [ (0, ), ] bc.categoryAxis.categoryNames = [ '' ] 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) (R,G,B) = VeriwaveYellow bc.bars[0].fillColor = colors.Color(R,G,B) bc.valueAxis.valueMin = self.valueMin bc.valueAxis.valueMax = self.valueMax bc.valueAxis.valueStep = self.valueStep bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 self.drawing.add(bc) #Put the labels on the center of the graph self._drawLabels(self.title, "Trial", "Clients")
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 generar_pdf_usuarios_mes(request): #print "Genero el PDF" mes =0 anio =0 story =[] fecha_usuarios = x response = HttpResponse(content_type='application/pdf') pdf_name = "reporte_usuarios_mes.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) reportes = [] styles = getSampleStyleSheet() fichero_imagen="biblioteca/media/images/Reports-banner.jpg" imagen_logo=Image(os.path.realpath(fichero_imagen),width=400,height=100) story.append(imagen_logo) reportes.append(imagen_logo) header = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1']) header2 = Paragraph("Reporte de los usuarios que prestaron espacio en el mes "+str(fecha_usuarios.month)+" del "+str(fecha_usuarios.year), styles['Normal']) salto_linea = Paragraph("\n\n", styles["Normal"]) reportes.append(Spacer(1, 12)) reportes.append(header) #reportes.append(Spacer(1, 12)) reportes.append(header2) reportes.append(Spacer(1, 12)) headings = ('Fecha préstamo', 'Usuario', 'Nombre del espacio', 'Fecha devolución') mes = x.month anio = x.year n = mes f = mes allreportes = [(i.fecha_prestamo, i.usuario.nombre, i.espacio.nombre_espacio, i.fecha_devolucion) for i in Prestamo.objects.filter(fecha_prestamo__month =mes,fecha_prestamo__year = anio)] #print allreportes t = Table([headings] + allreportes) t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) #GRAFICA DE BARRAS titulo1 = Paragraph("Gráfica comparativa de usuarios que prestaron espacios en el mes "+str(fecha_usuarios.month)+" y el mes anterior a éste. ", estilo['title']) drawing = Drawing(400, 200) data = [(u1, u2)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.bars[0].fillColor = colors.blue bc.bars[1].fillColor = colors.red bc.strokeColor = colors.black bc.fillColor = colors.silver bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = u2+10 try: o = u2 / 2 if type(o) == 'float': bc.valueAxis.valueStep = u2+0.5 if type(o) == 'int': bc.valueAxis.valueStep = o except: "No se puede" bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 if mes == 1: n = mes + 11 else: f = mes - 1 bc.categoryAxis.categoryNames = [ datetime.date(anio, f, 1).strftime('%B'), datetime.date(anio, n, 1).strftime('%B')] drawing.add(bc) bc.barLabels.nudge = 20 bc.barLabelFormat = '%0.0f' bc.barLabels.dx = 0 bc.barLabels.dy = 0 bc.barLabels.boxAnchor = 'n' # irrelevant (becomes 'c') bc.barLabels.fontName = 'Helvetica' bc.barLabels.fontSize = 14 reportes.append(t) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(titulo1) reportes.append(drawing) doc.build(reportes) response.write(buff.getvalue()) buff.close() return response
def create_single_grade_pdf(student_id, class_id, assignment_count, grade_standard_dict, grade_student_dict, assignment_line_all, assignment_names, assignment_dict): '''--Variables--''' Story=[] Elements=[] buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages=[[]] standard_table=[] #content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the student Name #Create the name for the PDf being returned pdfName = get_student_name(student_id).first_name+"_"+get_student_name(student_id).last_name+"_SR"+".pdf" #set up the response headers so the browser knows to return a PDF document response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] ='attachment;filename=%s;'%pdfName doc = SimpleDocTemplate(buff,pagesize=letter,rightMargin=72,leftMargin=72,topMargin=72,bottomMargin=18) doc.title=pdfName #Set up some styles styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Indent', rightIndent=3)) styles.add(ParagraphStyle(name = 'Title2', parent = styles['Normal'], fontName = 'DejaVuSansCondensed', fontSize = 18, leading = 22, #alignment = TA_LEFT, spaceAfter = 6), alias = 'title2') #Time-Stamp ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Administrator ptext='<font size=12><b>%s %s</b></font>'%(get_student_name(student_id).first_name, get_student_name(student_id).last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>%s Student Report</b></font>'%(get_class_name(class_id).name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) #Total Assignments ptext = '<font size=12>Total Assignments: %s</font>'%(assignment_count) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1,20)) #Graph Title ptext = '<font size=15><b>Current Performance by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,50)) #get all the standards for a specific grade and content area standard_query = ((db.classes.id == class_id)& (student_id == db.student.id)& (db.classes.id == db.student_classes.class_id)& (db.student.id == db.student_classes.student_id)& (db.student.id == db.student_grade.student_id)& (db.grade.id == db.student_grade.grade_id)& (db.grade.id == db.grade_standard.grade_id)& (db.standard.id == db.grade_standard.standard_id)& (db.classes.id == db.class_grade.class_id)& (db.grade.id == db.class_grade.grade_id)& (db.standard.content_area == db.contentarea.id)) standard_list = db(standard_query).select(db.standard.id, db.standard.short_name, db.standard.reference_number,db.student_grade.student_score, db.grade.score, db.contentarea.name) standard_ref_list=[] #Setup the Dictionary of standard averages standard_dict = {} standard_table = [] standard_averages=[[]] for row in standard_list: if row.standard.id in standard_dict.keys(): if((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)): max_score = standard_dict[row.standard.id][0] + row.grade.score student_score = standard_dict[row.standard.id][1] + row.student_grade.student_score standard_dict[row.standard.id] = [max_score, student_score, row.standard.reference_number, row.standard.short_name] else: standard_dict[row.standard.id] = [row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name] i = 0 #set up the 2D list of Standard Averages for standard in sorted(standard_dict.keys()): standard_ref_list.append(standard_dict[standard][2]) standard_table.append([]) current_avg = (standard_dict[standard][1]/standard_dict[standard][0])*100 if minimum > current_avg: minimum = current_avg #int/round was here standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%") #int/round was here standard_averages[0].append((standard_dict[standard][1]/standard_dict[standard][0])*100) for grade in grade_standard_dict.keys(): for standardId in grade_standard_dict[grade][1]: if(standardId == standard): standard_table[i].append(grade_standard_dict[grade][0]+":"+format((grade_student_dict[grade][1]/grade_student_dict[grade][0])*100, '.2f')+"%") i+=1 sorted(standard_table,key=lambda l:l[0]) '''---Graph---''' drawing = Drawing(600, 200) data = standard_averages bc = VerticalBarChart() #location in the document (x,y) bc.x = 10 bc.y = 30 #width and height of the graph bc.height = 225 bc.width = 400 bc.data = data bc.categoryAxis.drawGridLast=True bc.categoryAxis.gridStart=0 bc.categoryAxis.gridStrokeLineCap = 2 bc.categoryAxis.gridEnd=3 #bc.barLabels = #Update colors of the bars in the graph bc.bars.symbol = ShadedRect() bc.bars.symbol.fillColorStart = colors.lightblue bc.bars.symbol.fillColorEnd = colors.lightblue bc.bars.symbol.strokeWidth = 0 #this draws a line at the top of the graph to close it. bc.strokeColor = colors.black #Y-axis min, max, and steps. if minimum != 100: bc.valueAxis.valueMin = minimum -10 else: bc.valueAxis.valueMin = 50 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 5 #where to anchor the origin of the graph bc.categoryAxis.labels.boxAnchor = 'ne' #Locations of labels for the X-axis bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -2 bc.barLabels.nudge = -10 bc.barLabelFormat = '%.2f%%' bc.barLabels.dx = 0 bc.barLabels.dy = 0 #The angle of the lables for the X-axis bc.categoryAxis.labels.angle = 30 #List of the categories to place on the X-axis bc.categoryAxis.categoryNames = standard_ref_list drawing.add(bc) '''------''' '''--Graph Legend--''' #Graph Legend legend = Legend() legend.alignment = 'right' legend.x = 420 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 legend.colorNamePairs = [(colors.lightblue, 'grade average')] drawing.add(legend, 'legend') drawing_title = "Bar Graph" Story.append(drawing) Story.append(Spacer(1,15)) #LineGraph Title ptext = '<font size=15><b>Class Performance by Assignment</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,30)) ''' Line Plot Graph ------ ''' assignment_data_all =[[],[]] for key in assignment_dict.keys(): assignment_data_all[0].append(assignment_dict[key][2]) assignment_data_all[1].append(assignment_dict[key][1]) drawing2 = Drawing(600, 200) data2 = assignment_data_all #lp = LinePlot() #data[0] = preprocessData(data[0]) lp = HorizontalLineChart() lp.x = -20 lp.y = 0 lp.height = 225 lp.width = 500 lp.data = data2 lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.lines[0].strokeColor = colors.grey lp.lines[1].strokeColor = colors.lightblue lp.strokeColor = colors.black lp.categoryAxis.labels.fontSize = 7 lp.categoryAxis.categoryNames = assignment_names lp.categoryAxis.labels.boxAnchor = 'ne' lp.categoryAxis.labels.angle = 30 lp.categoryAxis.drawGridLast=True #lp.categoryAxis.gridStart=0 lp.categoryAxis.gridStrokeLineCap = 2 #lp.categoryAxis.gridEnd=3 #lp.categoryAxis.visibleGrid = 1 lp.valueAxis.visibleGrid = 1 lp.valueAxis.visible = 1 lp.valueAxis.drawGridLast=False #lp.valueAxis.gridStart = 0 #lp.valueAxis.gridEnd = 100 lp.valueAxis.gridStrokeColor = colors.black lp.valueAxis.valueMin = 0 lp.valueAxis.valueMax = 105 lp.valueAxis.valueStep = 10 lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.fillColor = colors.white drawing2.add(lp) legend = Legend() legend.alignment = 'right' legend.x = 482 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 2 legend.colorNamePairs = [(colors.lightblue, 'Student'),(colors.grey, 'Class')] drawing2.add(legend, 'legend') Story.append(drawing2) Story.append(Spacer(1,30)) ptext = '<font size=15><b>Assignments by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,10)) t=Table(standard_table) t.setStyle(t.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 7), ('BACKGROUND',(0,0),(0,-1),colors.lightgrey), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),]))) Story.append(t) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def makeDocument(filename, pageCallBack=None): #the extra arg is a hack added later, so other #tests can get hold of the canvas just before it is #saved global titlelist, closeit titlelist = [] closeit = 0 c = Canvas(filename) c.setPageCompression(0) c.setPageCallBack(pageCallBack) framePageForm(c) # define the frame form framePage(c, 'PDFgen graphics API test script') makesubsection(c, "PDFgen", 10 * inch) story = [] #add some flowables story.append(box(Paragraph("Champions", styleT))) story.append(Paragraph("Philosophizing", styleH)) story.append(Paragraph(""" This is a paragraph in <i>Normal</i> style. We do understand exactly why the system hates me. I really really hate the autocorrect. I really do not mind the tab-complete function, but the rest of this is shit.""", styleN)) data = [[query("cid"), query("total_price"), query("gross_margin"), '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']] t = Table(data) t.setStyle(TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green), ('TEXTCOLOR', (0, 0), (1, -1), colors.red)])) story.append(t) f = Frame(inch, inch, 6.5 * inch, 9 * inch, showBoundary=0) f.addFromList(story, c) c.showPage() # END OF PAGE 1 framePage(c, 'Line Drawing Styles') st = [] st.append(Spacer(0, 0.5 * inch)) g = Drawing(3, 4) f2 = Frame(inch, inch, 6.5 * inch, 9 * inch, showBoundary=0) #St.append(g.add(star(c, title="Title", aka="comments", xcenter=2 * inch, # ycenter=3 * inch, nvertices=5))) chart = VerticalBarChart() # Set the starting point to be (0, 0). Changing this value changes # the position that the chart is rendered at within it's 'Drawing' # space, which we create below. chart.x = 0 chart.y = 0 # This determines the width, in centimeters (you could use 'inch' # as well) of the chart on the paper, as well as the height. chart_width = 5 * inch chart_height = 4 * inch chart.height = chart_height chart.width = chart_width # The vertical ticks will be labeled from 0 with a value every # 15 units, spaced so that the maximum value is 60. chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 60 chart.valueAxis.valueStep = 15 # Put the labels at the bottom with an interval of 8 units, # -2 units below the axis, rotated 30 degrees from horizontal chart.categoryAxis.labels.dx = 8 chart.categoryAxis.labels.dy = -2 chart.categoryAxis.labels.angle = 30 # The text box's NE corner (top right) is located at the above # coordinate chart.categoryAxis.labels.boxAnchor = 'ne' # Our various horizontal axis labels catNames = ['Jan-06', 'Feb-06', 'Mar-06', 'Apr-06', 'May-06', 'Jun-06', 'Jul-06', 'Aug-06'] chart.categoryAxis.categoryNames = catNames # Some random data to populate the chart with. chart.data = [(8, 5, 20, 22, 37, 28, 30, 47)] # Since the 'Chart' class itself isn't a 'Flowable', we need to # create a 'Drawing' flowable to contain it. We want the basic # area to be the same size as the chart itself, so we will # initialize it with the chart's size. g = Drawing(chart_width, chart_height) g.add(chart) # Add the Chart containing Drawing to our elements list st.append(box(g)) g.add(star(c, title="Right", aka="comments", xcenter=7 * inch, ycenter=7 * inch, nvertices=5)) g.add(star(c, title="Left", aka="comments", xcenter=3 * inch, ycenter=7 * inch, nvertices=6)) st.append(Spacer(1, 1 * inch)) st.append(box(Paragraph(""" Well, its now hard to argue that this is working pretty well. Possibly make some nice output charts, and import an image.""", styleH))) f2.addFromList(st, c) c.showPage() c.save() return c
disc(""" As usual, we will start with an example: """) from reportlab.graphics.shapes import Drawing from reportlab.graphics.charts.barcharts import VerticalBarChart drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99',