python绘图工具reportlab介绍

来源:http://blog.csdn.net/happyteafriends/article/details/9418341

转载原因:直接复制代码碰到点问题,等下记录下


官方介绍:

Generating PDFs from Wall Street to Wikipedia

We build solutions to generate rich, attractive and fully bespoke PDF documents at incredible speeds. This can let you serve personalised documents in real time, produce high-quality output, and support all kinds of delivery from web downloads through to personalised digital print.

简要来说,就是 快速实时生成丰富的、定制的PDF文档。用于实时个性化定制,生成高质量的输出,支持各种交付,可以从网络下载到个人输出等。


安装:

  1. #  yum install freetype-devel.x86_64   
  2. #  yum install python-devel.x86_64  
  3.   
  4. #  pip install reportlab  
如果不安装python-devel否则报错:
  1. #  error: command 'gcc' failed with exit status 1 Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build-root/reportlab/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-oneoII-record/install-record.txt --single-version-externally-managed failed with error code 1 in /tmp/pip-build-root/reportlab  


几个例子:

坐标图:

  1. from reportlab.lib import colors  
  2. from urllib import urlopen  
  3. from reportlab.graphics.shapes import *  
  4. from reportlab.graphics.charts.lineplots import LinePlot  
  5. from reportlab.graphics import renderPDF  
  6.   
  7. URL="http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt"  
  8. COMMENT_CHARS='#:'  
  9.   
  10. drawing = Drawing(400,200)  
  11. data = []  
  12. for  line in  urlopen(URL).readlines():  
  13.     if not line.isspace() and not line[0in COMMENT_CHARS:  
  14.         data.append([float(n) for n in line.split()])  
  15.   
  16. pred = [row[2for row in data]  
  17. high = [row[3for row in data]  
  18. low = [row[4for row in data]  
  19. times = [row[0] + row[1]/12.0 for row in data]  
  20.   
  21. lp = LinePlot()  
  22. lp.x = 50  
  23. lp.y = 50  
  24. lp.height = 125  
  25. lp.width = 300  
  26. lp.data = [zip(times,pred),zip(times,high),zip(times,low)]  
  27. drawing.add(lp)  
  28.   
  29. renderPDF.drawToFile(drawing,'report.pdf','Sunspots')  
  30.   
  31. def main():  
  32.   
  33.     return 0  
  34.   
  35. if __name__ == '__main__':  
  36.     main()  




坐标柱状图:

  1. from reportlab.lib.colors import Color, blue, red  
  2. from reportlab.graphics.charts.legends import Legend, TotalAnnotator  
  3. from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin  
  4. from standard_colors import pdf_chart_colors, setItems  
  5. from reportlab.lib.validators import Auto  
  6. from reportlab.graphics.charts.barcharts import VerticalBarChart  
  7.   
  8. class FactSheetHoldingsVBar(_DrawingEditorMixin,Drawing):  
  9.     def __init__(self,width=400,height=200,*args,**kw):  
  10.         apply(Drawing.__init__,(self,width,height)+args,kw)  
  11.         self._add(self,VerticalBarChart(),name='bar',validate=None,desc=None)  
  12.         self.bar.data             = [[4.22], [4.12], [3.65], [3.56], [3.49], [3.44], [3.07], [2.84], [2.76], [1.09]]  
  13.         self.bar.categoryAxis.categoryNames = ['Financials','Energy','Health Care','Telecoms','Consumer','Consumer 2','Industrials','Materials','Other','Liquid Assets']  
  14.         self.bar.categoryAxis.labels.fillColor = None  
  15.         self.bar.width                      = 200  
  16.         self.bar.height                     = 150  
  17.         self.bar.x                          = 30  
  18.         self.bar.y                          = 15  
  19.         self.bar.barSpacing                 = 5  
  20.         self.bar.groupSpacing               = 5  
  21.         self.bar.valueAxis.labels.fontName  = 'Helvetica'  
  22.         self.bar.valueAxis.labels.fontSize  = 8  
  23.         self.bar.valueAxis.forceZero        = 1  
  24.         self.bar.valueAxis.rangeRound       = 'both'  
  25.         self.bar.valueAxis.valueMax         = None#10#  
  26.         self.bar.categoryAxis.visible       = 1  
  27.         self.bar.categoryAxis.visibleTicks  = 0  
  28.         self.bar.barLabels.fontSize         = 6  
  29.         self.bar.valueAxis.labels.fontSize  = 6  
  30.         self.bar.strokeWidth                = 0.1  
  31.         self.bar.bars.strokeWidth           = 0.5  
  32.         n                                   = len(self.bar.data)  
  33.         setItems(n,self.bar.bars,'fillColor',pdf_chart_colors)  
  34.         #add and set up legend  
  35.         self._add(self,Legend(),name='legend',validate=None,desc=None)  
  36.         _ = ['Vodafone Group''UBS''British Petroleum''Royal bk of Scotland''HSBC Holdings''Total Elf Fina''Repsol''Novartis''BNP Paribas''Schneider Electric' ]  
  37.         self.legend.colorNamePairs  = [(Auto(chart=self.bar),(t,'%.2f'% d[0])) for t,d in zip(_,self.bar.data)]  
  38.         self.legend.columnMaximum   = 10  
  39.         self.legend.fontName        = 'Helvetica'  
  40.         self.legend.fontSize        = 5.5  
  41.         self.legend.boxAnchor       = 'w'  
  42.         self.legend.x               = 260  
  43.         self.legend.y               = self.height/2  
  44.         self.legend.dx              = 8  
  45.         self.legend.dy              = 8  
  46.         self.legend.alignment       = 'right'  
  47.         self.legend.yGap            = 0  
  48.         self.legend.deltay          = 11  
  49.         self.legend.dividerLines    = 1|2|4  
  50.         self.legend.subCols.rpad    = 10  
  51.         self.legend.dxTextSpace     = 5  
  52.         self.legend.strokeWidth     = 0  
  53.         self.legend.dividerOffsY    = 6  
  54.         self.legend.colEndCallout   = TotalAnnotator(rText='%.2f'%sum([x[0for x in self.bar.data]), fontName='Helvetica-Bold', fontSize=self.legend.fontSize*1.1)  
  55.         self.legend.colorNamePairs  = [(self.bar.bars[i].fillColor, (self.bar.categoryAxis.categoryNames[i][0:20], '%0.2f' % self.bar.data[i][0])) for i in range(len(self.bar.data))]  
  56.   
  57.   
  58.   
  59. def main():   
  60.     drawing = FactSheetHoldingsVBar()  
  61.     drawing.save(formats=['pdf'],outDir='.',fnRoot=None)  
  62.     drawing.save(formats=['png'],outDir='.',fnRoot=None)  
  63.     return 0  
  64.   
  65. if __name__ == '__main__':  
  66.     main()  


绘制饼图:

  1. from reportlab.graphics.charts.piecharts import Pie  
  2. from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin  
  3. from reportlab.lib.colors import Color, magenta, cyan  
  4.   
  5. class pietests(_DrawingEditorMixin,Drawing):  
  6.     def __init__(self,width=400,height=200,*args,**kw):  
  7.         Drawing.__init__(self,width,height,*args,**kw)  
  8.         self._add(self,Pie(),name='pie',validate=None,desc=None)  
  9.         self.pie.sideLabels       = 1  
  10.         self.pie.labels           = ['Label 1''Label 2''Label 3''Label 4''Label 5']  
  11.         self.pie.data             = [2010555]  
  12.         self.pie.width            = 140  
  13.         self.pie.height           = 140  
  14.         self.pie.y                = 35  
  15.         self.pie.x                = 125  
  16.   
  17.   
  18. def main():  
  19.     drawing = pietests()  
  20.     # you can do all sorts of things to drawing, lets just save it as pdf and png.  
  21.     drawing.save(formats=['pdf','png'],outDir='.',fnRoot=None)  
  22.     return 0  
  23.   
  24. if __name__ == '__main__':  
  25.     main()  

效果:


官网:

http://www.reportlab.com/

文档:

http://www.reportlab.com/software/documentation/

示例:

http://www.reportlab.com/snippets/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值