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.
View all snippets
Just another ordinary pie chart
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._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' self.chart.height = 99 self.chart.width = 99 self.legend.alignment = 'right' self.legend.columnMaximum = 9 self.legend.fontSize = 13 # these data can be read from external sources data = (5, 4, 3, 2, 1) categories = ('sale','marketing','travel','health','misc') colors = [PCMYKColor(100,50,30,x) for x in (50,40,30,20,10)] 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__": #NORUNTESTS MyDrawing().save(formats=['pdf','png'],outDir='.',fnRoot=None)