Code snippets are bits of re-usable code submitted by the ReportLab community. We don't promise that they are accurate, up-to-date or correct - use them at your own risk!
We'd love it if you could participate by submitting your own snippets and sharing your experience with others by commenting. You will need to create a user account by filling out our very simple form.
This shows a Pie chart with a Legend, being saved as both a bitmap for the web and a PDF chart. This code was generated using Diagra (ReportLab's commercial charts package), which allows you to define charts in a GUI. However, you don't need this package to run it, and all the chart features demonstrated are available in our open source package.
# Autogenerated by ReportLab guiedit do not edit # this code was generated by Diagra, ReportLab Commercial drawing editor # It took only few clicks to generate the code. from reportlab.lib.pagesizes import cm, inch from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.charts.legends import Legend from reportlab.lib.colors import Color, PCMYKColor from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin class MyDrawing(_DrawingEditorMixin,Drawing): def __init__(self,width=400,height=200,*args,**kw): apply(Drawing.__init__,(self,width,height)+args,kw) self._add(self,Pie(),name='chart',validate=None,desc=None) self.chart.x = 20 self.chart.y = (self.height-self.chart.height)/2 self.chart.slices.strokeWidth = 1 self.chart.slices.popout = 1 self.chart.direction = 'clockwise' self.chart.width = self.chart.height self.chart.startAngle = 90 self.chart.slices.popout = 10 self._add(self,Legend(),name='legend',validate=None,desc=None) self.legend.x = width - 20 self.legend.y = 0 self.legend.boxAnchor = 'se' self.legend.subCols.align = 'right' # these data can be read from external sources data = (9, 7, 6, 4, 2.5, 1.0) categories = ('A','B','C','D','E','F',) colors = [PCMYKColor(0,0,0,x) for x in (100,80,60,40,20,5)] self.chart.data = data self.chart.labels = map(str, self.chart.data) self.legend.colorNamePairs = zip(colors, categories) for i, color in enumerate(colors): self.chart.slices[i].fillColor = color if __name__=="__main__": drawing = MyDrawing() # you can do all sorts of things to drawing, lets just save it as pdf and png. drawing.save(formats=['pdf','png'],outDir='.',fnRoot=None)