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 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 drawing_chinese(): from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.charts.textlabels import Label from reportlab.graphics import renderPDF from reportlab.graphics.widgets.markers import makeMarker data = [((1, 100), (2, 200), (3, 300), (4, 400), (5, 500)), ((1, 50), (2, 80), (3, 400), (4, 40), (5, 70))] drawing = Drawing(500, 300) lp = LinePlot() lp.x = 50 #������������ lp.y = 30 lp.height = 250 lp.width = 400 lp.data = data lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.xValueAxis.valueMin = 1 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 500 lp.yValueAxis.valueStep = 100 drawing.add(lp) title = Label() #����Ҫ��ʾ���ģ���Ҫ��ע��һ���������� title.fontName = "msyh" title.fontSize = 12 title_text = u'你好吗' #title_text = "abc" title._text = title_text title.x = 250 title.y = 280 title.textAnchor = 'middle' drawing.add(title) Xlabel = Label() Xlabel._text = 'x' Xlabel.fontSize = 12 Xlabel.x = 480 Xlabel.y = 30 Xlabel.textAnchor = 'middle' drawing.add(Xlabel) Ylabel = Label() Ylabel._text = "y" Ylabel.fontSize = 12 Ylabel.x = 40 Ylabel.y = 295 Ylabel.textAnchor = 'middle' drawing.add(Ylabel) try: drawing.save(formats=['gif'], outDir=".", fnRoot="abc") except: import traceback traceback.print_exc()
def line_plot_demo(): d = Drawing(400, 400) line = LinePlot() line.x = 50 line.y = 85 line.height = 150 line.width = 250 line.lineLabelFormat = '%2.0f' data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))] line.data = data line.lines[0].strokeColor = colors.green line.lines[1].strokeColor = colors.blue line.lines[0].strokeWidth = 3 line.lines[0].symbol = makeMarker('Circle') line.lines[1].symbol = makeMarker('Hexagon') line.xValueAxis.valueMin = 0 line.xValueAxis.valueMax = 10 line.xValueAxis.valueSteps = [1, 2, 4] line.xValueAxis.labelTextFormat = '%2.1f' line.yValueAxis.valueMin = 0 line.yValueAxis.valueMax = 12 d.add(line, '') d.save(formats=['pdf'], outDir='.', fnRoot='line_plot_demo')
def tearDownClass(cls): if not cls.IMAGES: return d = Drawing(A4[0], A4[1]) for img in cls.IMAGES: d.add(img) outPath = outputfile("test_graphics_images.pdf") renderPDF.drawToFile(d, outPath) #, '') assert os.path.exists(outPath) try: import rlPyCairo except ImportError: rlPyCairo = None from reportlab.rl_config import renderPMBackend d.save(formats=['png', 'gif', 'ps', 'svg'], outDir=os.path.dirname(outPath), fnRoot='test_graphics_images', _renderPM_backend='_renderPM') if rlPyCairo: d.save(formats=['png', 'gif'], outDir=os.path.dirname(outPath), fnRoot='test_graphics_images-cairo', **(dict(_renderPM_backend='rlPyCairo') if renderPMBackend == '_renderPM' else {}))
def flag_demo(): drawing = Drawing(width=612, height=792) y = 692 flag = flags.Flag(kind='USA') flag.y = y drawing.add(flag) label = String(95, y - 15, 'USA', fontSize=14, textAnchor='middle') drawing.add(label) countries = flag.availableFlagNames() countries.pop(1) country = 1 for flag in range(5): flag = flags.Flag() flag.kind = countries[country] flag.y = y - 125 drawing.add(flag) label = String(95, flag.y - 15, countries[country], fontSize=14, textAnchor='middle') drawing.add(label) country += 1 y -= 125 drawing.save(formats=['pdf'], outDir='.', fnRoot='flag_demo')
def simple_pie_chart_label_customization(): data = [10, 20, 30, 40] drawing = Drawing() pie = Pie() pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcd'] # enable label customization pie.simpleLabels = 0 # add some customization pie.slices[0].label_angle = 45 pie.slices[0].label_text = 'foobar' # normal pie properties pie.slices.strokeWidth = 0.5 pie.slices[3].popout = 20 pie.slices[3].strokeDashArray = [1, 1] drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart_label_customization')
def solid_shapes(): drawing = Drawing(width=400, height=200) rectangle = Rect(10, 10, 100, 100) rectangle.fillColor = colors.blue drawing.add(rectangle) ellipse = Ellipse(100, 50, 50, 25) ellipse.fillColor = colors.red drawing.add(ellipse) circle = Circle(50, 170, 25) circle.fillColor = colors.green drawing.add(circle) wedge = Wedge(150, 150, 65, startangledegrees=0, endangledegrees=45) wedge.fillColor = colors.yellow drawing.add(wedge) poly = Polygon(points=[250, 150, 280, 150, 280, 100, 250, 100 ]) poly.fillColor = colors.purple drawing.add(poly) drawing.save(formats=['pdf'], outDir='.', fnRoot='solid_shapes')
def qr_code_drawing(text_value, name): qrw = QrCodeWidget(text_value) b = qrw.getBounds() w = b[2] - b[0] h = b[3] - b[1] d = Drawing(120, 120, transform=[120. / w, 0, 0, 120. / h, 0, 0]) d.add(qrw) d.save(formats=['png'], outDir='media/barcode/', fnRoot=str(name))
def test_qr_code_with_comma(self): from reportlab.graphics.barcode.qr import QrCodeWidget from reportlab.graphics.shapes import Drawing i = QrCodeWidget("VALUE WITH A COMMA,") x0, y0, x1, y1 = i.getBounds() D = Drawing(x1-x0, y1-y0) D.add(i) D.save(['gif','pict','pdf'], outDir=self.outDir, fnRoot="QR_with_comma")
def create_circle(): drawing = Drawing(width=400, height=200) circle = Circle(50, 170, 25) circle.fillColor = colors.green circle.strokeColor = colors.red circle.strokeWidth = 5 drawing.add(circle) drawing.save(formats=['pdf'], outDir='.', fnRoot='circle')
def draw_recent_week_pdf(filename, data_list): """ 画最近七天的流量计报表 :param filename: :param data_list :return: """ data = [] max_val = 0 for index in range(0, len(data_list)): data.append((index + 1, data_list[index])) max_val = max(max_val, data_list[index]) drawing = Drawing(500, 800) lp = LinePlot() lp.x = 50 lp.y = 80 lp.height = 600 lp.width = 400 lp.data = [data] lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.xValueAxis.valueMin = 1 lp.xValueAxis.valueMax = 7 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = (int(max_val / 100) + 1) * 100 lp.yValueAxis.valueStep = 100 drawing.add(lp) x_title = Label() # 若需要显示中文,需要先注册一个中文字体 pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc")) x_title.fontName = "haha" x_title.fontSize = 12 title_text = '用气量' x_title._text = title_text x_title.x = 20 x_title.y = 100 x_title.textAnchor = 'middle' drawing.add(x_title) y_title = Label() # 若需要显示中文,需要先注册一个中文字体 pdfmetrics.registerFont(ttfonts.TTFont("haha", "simsun.ttc")) y_title.fontName = "haha" y_title.fontSize = 12 title_text = '最近七天' y_title._text = title_text y_title.x = 80 y_title.y = 50 y_title.textAnchor = 'middle' drawing.add(y_title) drawing.save(formats=['pdf'], outDir=TMP_FILE_DIRECTORY_PATH, fnRoot=filename)
def line_demo(): drawing = Drawing(width=400, height=200) line = Line(25, 25, 150, 150) line.strokeColor = colors.red line.strokeWidth = 5 drawing.add(line) points = [25, 50, 35, 100, 100, 50, 150, 150] poly = PolyLine(points=points, strokeWidth=3, strokeColor=colors.blue) drawing.add(poly) drawing.save(formats=['pdf'], outDir='.', fnRoot='line_demo')
def qr_code_drawing(text_value, name): qrw = QrCodeWidget(text_value) b = qrw.getBounds() w = b[2] - b[0] h = b[3] - b[1] d = Drawing(120, 120, transform=[120. / w, 0, 0, 120. / h, 0, 0]) d.add(qrw) dir = settings.BASE_DIR d.save(formats=['png'], outDir=os.path.join(dir, 'static/barcode'), fnRoot=str(name))
def diagrammKostenartVonBis(self, aPfad, aDateiname, aData, aLabels): d = Drawing(800, 800) pie = Pie() pie.x = 360 pie.y = 360 pie.xradius = 300 pie.yradius = 300 pie.data = aData pie.labels = aLabels pie.slices.strokeWidth = 0.5 # pie.slices[3].popout = 20 d.add(pie) d.save(formats=['png'], outDir=aPfad, fnRoot=aDateiname)
def simple_pie_chart(): data = [10, 20, 30, 40] drawing = Drawing() pie = Pie() pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcd'] pie.slices.strokeWidth = 0.5 pie.slices[3].popout = 20 pie.slices[3].strokeDashArray = [1, 1] drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart')
def create_bar_graph(arr, name, title, c, m, y, k): d = Drawing(280, 250) bar = VerticalBarChart() bar.x = 50 bar.y = 85 data = [arr] bar.data = data bar.categoryAxis.categoryNames = title bar.bars[0].fillColor = PCMYKColor(c, m, y, k, 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=statsPath + name)
def simple_pie_chart_side_labels(): data = list(range(15, 105, 15)) drawing = Drawing() pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcdefg'] pie.slices.strokeWidth = 0.5 drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart_side_labels')
def group_demo(): drawing = Drawing(width=400, height=200) radius = 25 circles = Group(Circle(50, 40, radius, fillColor=colors.blue), Circle(75, 40, radius, fillColor=colors.red), Circle(100, 40, radius, fillColor=colors.green), Circle(125, 40, radius, fillColor=colors.yellow), String(75, 5, 'Circles')) drawing.add(circles) more_circles = Group(circles) more_circles.translate(75, 55) more_circles.rotate(35) drawing.add(more_circles) drawing.save(formats=['pdf'], outDir='.', fnRoot='group_demo')
def pie_chart_with_legend(): data = list(range(15, 105, 15)) drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'My Pie Chart', fontSize=14) pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = None pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) add_legend(drawing, pie, data) drawing.save(formats=['pdf'], outDir='.', fnRoot='pie_chart_with_legend')
def simple_pie_chart_with_title(): data = list(range(15, 105, 15)) drawing = Drawing(width=400, height=200) my_title = String(170, 40, 'My Pie Chart', fontSize=14) pie = Pie() pie.sideLabels = True pie.x = 150 pie.y = 65 pie.data = data pie.labels = [letter for letter in 'abcdefg'] pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) drawing.save(formats=['pdf'], outDir='.', fnRoot='simple_pie_chart_with_title')
def test0(self): from reportlab.graphics.shapes import Drawing outDir = self.outDir html = ['<html><head></head><body>'] a = html.append formats = ['gif','pict','pdf'] from reportlab.graphics.barcode import getCodes CN = list(getCodes().items()) for name,C in CN: i = C() D = Drawing(100,50) D.add(i) D.save(formats=formats,outDir=outDir,fnRoot=name) a('<h2>%s</h2><img src="%s.gif"><br>' % (name, name)) for fmt in formats: efn = os.path.join(outDir,'%s.%s' % (name,fmt)) self.assertTrue(os.path.isfile(efn),msg="Expected file %r was not created" % efn) a('</body></html>') open(os.path.join(outDir,'index.html'),'w').write('\n'.join(html))
def string_demo(): drawing = Drawing(width=400, height=200) for size in range(10, 32, 4): x = 15 + size * 1.5 y = 15 + size * 1.5 my_string = String(x, y, 'Python rocks!') my_string.fontName = 'Courier' my_string.fontSize = size drawing.add(my_string) other_string = String(200, 150, 'Centered Text') other_string.fontName = 'Times-Roman' other_string.fontSize = 40 other_string.fillColor = colors.red other_string.textAnchor = 'middle' drawing.add(other_string) drawing.save(formats=['pdf'], outDir='.', fnRoot='string_demo')
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 test0(self): from reportlab.graphics.shapes import Drawing outDir = self.outDir html = ['<html><head></head><body>'] a = html.append formats = ['gif','pict','pdf'] from reportlab.graphics.barcode import getCodes CN = list(getCodes().items()) for name,C in CN: i = C() x0,y0,x1,y1 = i.getBounds() D = Drawing(x1-x0,y1-y0) D.add(i) D.save(formats=formats,outDir=outDir,fnRoot=name) a('<h2>%s</h2><img src="%s.gif"><br>' % (name, name)) for fmt in formats: efn = os.path.join(outDir,'%s.%s' % (name,fmt)) self.assertTrue(os.path.isfile(efn),msg="Expected file %r was not created" % efn) a('</body></html>') open(os.path.join(outDir,'index.html'),'w').write('\n'.join(html))
def face_demo(): drawing = Drawing(width=400, height=200) sad_face = widgetbase.Face() sad_face.skinColor = colors.blue sad_face.mood = 'sad' drawing.add(sad_face) ok_face = widgetbase.Face() ok_face.skinColor = colors.beige ok_face.mood = 'ok' ok_face.x = 110 drawing.add(ok_face) happy_face = widgetbase.Face() happy_face.skinColor = colors.yellow happy_face.mood = 'happy' happy_face.x = 215 drawing.add(happy_face) drawing.save(formats=['pdf'], outDir='.', fnRoot='face_demo')
def create_bar_graph(): d = Drawing(250, 220) bar = VerticalBarChart() bar.x = 50 bar.y = 85 data = [[12,2,3,None,None,None,5], [5,7,2,8,8,2,5], [2,10,2,1,8,9,5], ] bar.data = data bar.categoryAxis.categoryNames = ['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=['jpg'], outDir='.', fnRoot='grafica')
def test(): """This function produces a pdf with examples. """ #wbite on blue rl = RL_CorpLogo() rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_whiteonblue',formats=['pdf','eps','jpg','gif']) #blue on white rl = RL_CorpLogoReversed() rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_blueonwhite',formats=['pdf','eps','jpg','gif']) rl = RL_BusinessCard() rl.x=25 rl.y=25 rl.border=1 D = Drawing(rl.width+50,rl.height+50) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='RL_BusinessCard',formats=['pdf'])
def test(): """This function produces a pdf with examples. """ # wbite on blue rl = RL_CorpLogo() rl.width = 129 rl.height = 86 D = Drawing(rl.width, rl.height) D.add(rl) D.__dict__["verbose"] = 1 D.save(fnRoot="corplogo_whiteonblue", formats=["pdf", "eps", "jpg", "gif"]) # blue on white rl = RL_CorpLogoReversed() rl.width = 129 rl.height = 86 D = Drawing(rl.width, rl.height) D.add(rl) D.__dict__["verbose"] = 1 D.save(fnRoot="corplogo_blueonwhite", formats=["pdf", "eps", "jpg", "gif"]) rl = RL_BusinessCard() rl.x = 25 rl.y = 25 rl.border = 1 D = Drawing(rl.width + 50, rl.height + 50) D.add(rl) D.__dict__["verbose"] = 1 D.save(fnRoot="RL_BusinessCard", formats=["pdf"])
def test0(self): from reportlab.graphics.shapes import Drawing outDir = self.outDir html = ["<html><head></head><body>"] a = html.append formats = ["gif", "pict", "pdf"] from reportlab.graphics.barcode import getCodes CN = list(getCodes().items()) for name, C in CN: i = C() x0, y0, x1, y1 = i.getBounds() D = Drawing(x1 - x0, y1 - y0) D.add(i) D.save(formats=formats, outDir=outDir, fnRoot=name) a('<h2>%s</h2><img src="%s.gif"><br>' % (name, name)) for fmt in formats: efn = os.path.join(outDir, "%s.%s" % (name, fmt)) self.assertTrue(os.path.isfile(efn), msg="Expected file %r was not created" % efn) a("</body></html>") open(os.path.join(outDir, "index.html"), "w").write("\n".join(html))
def report_pdf(request): feedbacks = Feedback.objects.all() ## import pygraphviz as P ## A=P.AGraph() # init empty graph ## # set some default node attributes ## A.node_attr['style']='filled' ## A.node_attr['shape']='circle' ## # Add edges (and nodes) ## A.add_edge(1,2) ## A.add_edge(2,3) ## A.add_edge(1,3) ## A.layout() # layout with default (neato) ## png=A.draw(format='png') # draw png ## return HttpResponse(png, mimetype='image/png') pdf_data = open('cfback/feed.pdf','rb').read() response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="feedback.pdf"' buffer = BytesIO() p = Drawing(400,200) ## p.add(String(300,175, "Feedbacks", textAnchor="middle")) pc = Pie() pc.x = 150 pc.y = 50 pc.data = [enumerate([i.title[0]]) for i in feedbacks] pc.labels = [str(y.company) for y in feedbacks] p.add(pc) ## p.showPage() p.save() pdf = buffer.getvalue() buffer.close response.write(pdf) return render_to_response('cfback/feed_report.html', response)
def generate_chart(self, data, x_labels, y_label, d_format): """Generates and saves a chart to disk, returning its local path""" # Create drawing to hold chart and legend (width, height) d = Drawing(self.W, self.H) # Create chart and legend cols = self.create_colors(len(data)) c = self.create_chart(data, y_label, d_format, cols) l = self.create_legend(x_labels, cols) # Add chart and legend to drawing d.add(c) d.add(l) # Get/Create full file path full_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.TEMP_PATH) if not os.path.exists(full_dir): os.makedirs(full_dir) # Export image as png and return save path save_path = os.path.join(full_dir, 'image.png') d.save(fnRoot=save_path, formats=['png']) return save_path
def test(): """This function produces a pdf with examples. """ #white on blue rl = RL_CorpLogo() rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_whiteonblue',formats=['pdf','eps','jpg','gif']) #blue on white rl = RL_CorpLogoReversed() rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_blueonwhite',formats=['pdf','eps','jpg','gif']) #gray on white rl = RL_CorpLogoReversed() rl.fillColor = Color(0.2, 0.2, 0.2) rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_grayonwhite',formats=['pdf','eps','jpg','gif']) rl = RL_BusinessCard() rl.x=25 rl.y=25 rl.border=1 D = Drawing(rl.width+50,rl.height+50) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='RL_BusinessCard',formats=['pdf'])
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors drawing = Drawing(400, 200) data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) drawing.save(formats=['pdf'], outDir='./pdfs', fnRoot='chart') # c = canvas.Canvas('./pdfs/chart_canvas.pdf') # c.da
50, 5, 5, fillColor=lightgrey, strokeColor=pink) _draw_3d_bar(D, 30, 40, 10, 45, 5, 5, fillColor=lightgrey, strokeColor=pink) D.save(formats=['pdf'], outDir='.', fnRoot='_draw_3d_bar') print( find_intersections([[(0, 0.5), (1, 0.5), (0.5, 0), (0.5, 1)], [(.2666666667, 0.4), (0.1, 0.4), (0.1, 0.2), (0, 0), (1, 1)], [(0, 1), (0.4, 0.1), (1, 0.1)]])) print(find_intersections([[(0.1, 0.2), (0.1, 0.4)], [(0, 1), (0.4, 0.1)]])) print( find_intersections([[(0.2, 0.4), (0.1, 0.4)], [(0.1, 0.8), (0.4, 0.1)]])) print(find_intersections([[(0, 0), (1, 1)], [(0.4, 0.1), (1, 0.1)]])) print( find_intersections([[(0, 0.5), (1, 0.5), (0.5, 0), (0.5, 1)], [(0, 0), (1, 1)], [(0.1, 0.8), (0.4, 0.1), (1, 0.1)]]))
class _isSymbol(Validator): def test(self, x): return ( hasattr(x, "__call__") or isinstance(x, Marker) or isinstance(x, Flag) or (type(x) == ClassType and issubclass(x, Widget)) ) isSymbol = _isSymbol() def makeMarker(name, **kw): if Marker._attrMap["kind"].validate(name): m = Marker(**kw) m.kind = name elif name[-5:] == "_Flag" and Flag._attrMap["kind"].validate(name[:-5]): m = Flag(**kw) m.kind = name[:-5] m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m if __name__ == "__main__": D = Drawing() D.add(Marker()) D.save(fnRoot="Marker", formats=["pdf"], outDir="/tmp")
from reportlab.graphics.shapes import Drawing os.chdir(os.path.dirname(sys.argv[0])) if not os.path.isdir('out'): os.mkdir('out') for x in glob.glob(os.path.join('out', '*')): os.remove(x) html = ['<html><head></head><body>'] a = html.append for C in ( BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State, ): name = C.__name__ i = C() D = Drawing(100, 50) D.add(i) D.save(formats=['gif', 'pict'], outDir='out', fnRoot=name) a('<h2>%s</h2><img src="%s.gif"><br>' % (name, name)) a('</body></html>') open(os.path.join('out', 'index.html'), 'w').write('\n'.join(html))
orientation = 'horizontal' angle = 0 rect = ShadedRect(strokeWidth=0, strokeColor=None, orientation=orientation) for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode': setattr(rect, k, getattr(self, k)) g.add(rotatedEnclosingRect(P, angle, rect)) g.add(EmptyClipPath) path = path.copy() path.isClipPath = 0 path.strokeColor = self.strokeColor path.strokeWidth = self.strokeWidth g.add(path) return g if __name__ == '__main__': #noruntests from reportlab.lib.colors import blue from reportlab.graphics.shapes import Drawing angle = 45 D = Drawing(120, 120) D.add( ShadedPolygon(points=(10, 10, 60, 60, 110, 10), strokeColor=None, strokeWidth=1, angle=90, numShades=50, cylinderMode=0)) D.save(formats=['gif'], fnRoot='shobj', outDir='/tmp')
chart.barLabels.nudge = 8 # Nudge labels upwards by 8px # ------- Create legend ------- legend = Legend() # Create the legend legend.boxAnchor = 'sw' # Set anchor to bottom-left legend.x = 50 # Shift legend right to bring in line with chart legend.y = 50 # Shift legend up by 50px legend.alignment = 'right' # Put labels to the right of color icons # Set legend colors legend.colorNamePairs = [(colors[i], '{} '.format(labels[i])) for i in range(len(colors))] # Add chart and legend to drawing d.add(chart) d.add(legend) # Export as test_img.png d.save(fnRoot='test_img', formats=['png']) #--------------------------------# # Opening an image from disk # #--------------------------------# # Though we use webbrowser module, it opens in whatever default app for the file type from webbrowser import open open('test_img.png')
if not ds: continue n = len(ds) if n==1: continue for i in xrange(1,n): seg = _Segment(s,i,data) if seg.a+abs(seg.b)>=small: a(seg) S.sort(_segCmp) I = [] n = len(S) for i in xrange(0,n-1): s = S[i] for j in xrange(i+1,n): if s.intersect(S[j],I)==1: break I.sort() return I if __name__=='__main__': from reportlab.graphics.shapes import Drawing from reportlab.lib.colors import lightgrey, pink D = Drawing(300,200) _draw_3d_bar(D, 10, 20, 10, 50, 5, 5, fillColor=lightgrey, strokeColor=pink) _draw_3d_bar(D, 30, 40, 10, 45, 5, 5, fillColor=lightgrey, strokeColor=pink) D.save(formats=['pdf'],outDir='.',fnRoot='_draw_3d_bar') print find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(.2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]]) print find_intersections([[(0.1, 0.2), (0.1, 0.4)], [(0, 1), (0.4, 0.1)]]) print find_intersections([[(0.2, 0.4), (0.1, 0.4)], [(0.1, 0.8), (0.4, 0.1)]]) print find_intersections([[(0,0),(1,1)],[(0.4,0.1),(1,0.1)]]) print find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(0,0),(1,1)],[(0.1,0.8),(0.4,0.1),(1,0.1)]])
def build_chart(feature_name, data, category_names, output_dir): from reportlab.graphics.shapes import Drawing, String from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.textlabels import Label from reportlab.lib import colors from reportlab.lib.validators import Auto # build chart and save it d = Drawing(800, 600) d.add(String(200,180,feature_name), name='title') chart = VerticalBarChart() chart.width = d.width-100 chart.height = d.height-75 chart.x = 40 chart.y = 40 chart.data = data chart.categoryAxis.categoryNames = category_names chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 2 chart.bars[0].fillColor = colors.red chart.bars[1].fillColor = colors.blue d.add(chart) d.title.x = d.width/2 d.title.y = d.height - 30 d.title.textAnchor ='middle' d.title.fontSize = 24 d.add(Legend(),name='Legend') d.Legend.colorNamePairs = [(chart.bars[i].fillColor, name) for i, name in enumerate(["Home Run", "Strikeout"])] d.Legend.fontName = 'Times-Roman' d.Legend.fontSize = 16 d.Legend.x = d.width-80 d.Legend.y = d.height-25 d.Legend.dxTextSpace = 5 d.Legend.dy = 5 d.Legend.dx = 5 d.Legend.deltay = 5 d.Legend.alignment ='right' d.add(Label(),name='XLabel') d.XLabel.fontName = 'Times-Roman' d.XLabel.fontSize = 12 d.XLabel.x = chart.x + chart.width/2 d.XLabel.y = 15 d.XLabel.textAnchor ='middle' d.XLabel._text = "Value" d.add(Label(),name='YLabel') d.YLabel.fontName = 'Times-Roman' d.YLabel.fontSize = 12 d.YLabel.x = 10 d.YLabel.y = chart.y + chart.height/2 d.YLabel.angle = 90 d.YLabel.textAnchor ='middle' d.YLabel._text = "Likelihood Index" d.save(fnRoot=os.path.join(output_dir, feature_name), formats=['png'])
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 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = graphs drawing.add(bc) drawing.save(fnRoot=algo + '_timing', formats=['pdf'])
ylbl = Label() ylbl.setText("Percentage\n (%)") ylbl.setOrigin(28, 260) lp.lines[0].strokeColor = colors.darkgreen lp.lineLabels[0].strokeColor = colors.darkgreen lp.lines[1].strokeColor = colors.tomato lp.lineLabels[1].strokeColor = colors.tomato lp.lines[2].strokeColor = colors.aquamarine lp.lineLabels[2].strokeColor = colors.aquamarine lp.lines[3].strokeColor = colors.purple lp.lineLabels[3].strokeColor = colors.purple lgnd = Legend() lgnd.x = 70 lgnd.y = 63 lgnd.autoXPadding = 45 lgnd.colorNamePairs = [ (lp.lines[0].strokeColor, 'Positive'), (lp.lines[1].strokeColor, 'Negative'), (lp.lines[2].strokeColor, 'Norm. Pos.'), (lp.lines[3].strokeColor, 'Norm. Neg.') ] lgnd.demo() d.add(lp) d.add(lgnd) d.add(xlbl) d.add(ylbl) d.save(fnRoot='testLinePlot1', formats=['png', 'pdf'])
lp.lines.symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.2f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.labelTextFormat = '%2.0f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 104 lp.yValueAxis.valueStep = 10 xlbl = Label() xlbl.setText("No. of Clusters") xlbl.setOrigin(310, 53) xlbl1 = Label() xlbl1.setText("No. Of Clusters Vs Accuracy") xlbl1.setOrigin(310, 25) ylbl = Label() ylbl.setText("Accuracy\n (%)") ylbl.setOrigin(28, 260) lp.lines[0].strokeColor = colors.purple lp.lineLabels[0].strokeColor = colors.purple d.add(lp) d.add(xlbl) d.add(xlbl1) d.add(ylbl) d.save(fnRoot='NoOfClustersVsAccuracy', formats=['png', 'pdf'])
self.points = [-1,-1,2,2,3,-1] LineShape.__init__(self,kw) def draw(self): P = self.points P = map(lambda i, P=P:(P[i],P[i+1]),xrange(0,len(P),2)) path = definePath([('moveTo',)+P[0]]+map(lambda x: ('lineTo',)+x,P[1:])+['closePath'], fillColor=None, strokeColor=None) path.isClipPath = 1 g = Group() g.add(path) rect = ShadedRect(strokeWidth=0,strokeColor=None) for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode': setattr(rect,k,getattr(self,k)) g.add(rotatedEnclosingRect(P, self.angle, rect)) g.add(EmptyClipPath) path = path.copy() path.isClipPath = 0 path.strokeColor = self.strokeColor path.strokeWidth = self.strokeWidth g.add(path) return g if __name__=='__main__': #noruntests from reportlab.lib.colors import blue from reportlab.graphics.shapes import Drawing angle=45 D = Drawing(120,120) D.add(ShadedPolygon(points=(10,10,60,60,110,10),strokeColor=None,strokeWidth=1,angle=90,numShades=50,cylinderMode=0)) D.save(formats=['gif'],fnRoot='shobj',outDir='/tmp')
from reportlab.graphics.shapes import Drawing from reportlab.lib.units import cm from reportlab import lib from reportlab.graphics.charts.linecharts import * # Tamaño del PDF drawing = Drawing(50 * cm, 25 * cm) # Grafica Horizontal lc = HorizontalLineChart() flowables = [] lc.data = [ (0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), (0, 64, 128, 192, 256, 320, 384, 448, 512, 576, 640, 1), ] legend = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"] lc.categoryAxis.categoryNames = legend lc.valueAxis.valueMin = 0 lc.height = 200 lc.width = 500 lc.x = 100 lc.y = 100 lc.valueAxis.valueMax = 1000 lc.valueAxis.valueStep = 200 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) # Generamos el fichero pdf, mediante el metodo drawing de la libreria reportlab drawing.save(formats=['pdf'], outDir=None, fnRoot='test') flowables.append(drawing)
symbol = uSymbol.clone() if isinstance(uSymbol,Marker): symbol.fillColor = symbol.fillColor or color symbol.x, symbol.y = x, y else: symbol = None return symbol class _isSymbol(Validator): def test(self,x): return hasattr(x,'__call__') or isinstance(x,Marker) or isinstance(x,Flag) \ or (type(x)==ClassType and issubclass(x,Widget)) isSymbol = _isSymbol() def makeMarker(name,**kw): if Marker._attrMap['kind'].validate(name): m = Marker(**kw) m.kind = name elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]): m = Flag(**kw) m.kind = name[:-5] m.size = 10 else: raise ValueError, "Invalid marker name %s" % name return m if __name__=='__main__': D = Drawing() D.add(Marker()) D.save(fnRoot='Marker',formats=['pdf'], outDir='/tmp')
if angle == 180: angle = 0 elif angle in (90, 270): orientation = "horizontal" angle = 0 rect = ShadedRect(strokeWidth=0, strokeColor=None, orientation=orientation) for k in "fillColorStart", "fillColorEnd", "numShades", "cylinderMode": setattr(rect, k, getattr(self, k)) g.add(rotatedEnclosingRect(P, angle, rect)) g.add(EmptyClipPath) path = path.copy() path.isClipPath = 0 path.strokeColor = self.strokeColor path.strokeWidth = self.strokeWidth g.add(path) return g if __name__ == "__main__": # noruntests from reportlab.lib.colors import blue from reportlab.graphics.shapes import Drawing angle = 45 D = Drawing(120, 120) D.add( ShadedPolygon( points=(10, 10, 60, 60, 110, 10), strokeColor=None, strokeWidth=1, angle=90, numShades=50, cylinderMode=0 ) ) D.save(formats=["gif"], fnRoot="shobj", outDir="/tmp")
import os, sys, glob from reportlab.graphics.shapes import Drawing os.chdir(os.path.dirname(sys.argv[0])) if not os.path.isdir('out'): os.mkdir('out') for x in glob.glob(os.path.join('out','*')): os.remove(x) html = ['<html><head></head><body>'] a = html.append for C in (BarcodeI2of5, BarcodeCode128, BarcodeStandard93, BarcodeExtended93, BarcodeStandard39, BarcodeExtended39, BarcodeMSI, BarcodeCodabar, BarcodeCode11, BarcodeFIM, BarcodePOSTNET, BarcodeUSPS_4State, ): name = C.__name__ i = C() D = Drawing(100,50) D.add(i) D.save(formats=['gif','pict'],outDir='out',fnRoot=name) a('<h2>%s</h2><img src="%s.gif"><br>' % (name, name)) a('</body></html>') open(os.path.join('out','index.html'),'w').write('\n'.join(html))
countries = [] for row in result.fetchall(): if c != unicode(row[0]): c = unicode(row[0]) countries.append(c) data_row += 1 data_col = 0 data_values.append([]) linelabels.append([]) data_values[data_row].append(float(str(row[4]))) if data_col == 0: linelabels[data_row].append(c) else: linelabels[data_row].append(None) data_col += 1 d = Drawing(800, 600) chart = HorizontalLineChart() chart.width = 740 chart.height = 560 chart.x = 50 chart.y = 20 chart.lineLabelArray = linelabels chart.lineLabelFormat = 'values' chart.data = data_values chart.categoryAxis.categoryNames = h_labels chart.valueAxis.valueMin = 0 d.add(chart) d.save(fnRoot='ghg-totals', formats=['png'])