A Vertical Bar Chart - ReportLab Snippets (Beta)

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


A Vertical Bar Chart
opensourcerl-toolkit

RLIMG: A Vertical Bar Chart
Author:
rptlab
Posted:
Dec. 3, 2009
Language:
Python
Tags:
opensource rl-toolkit

This shows a Horizontal Bar 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.

# this code was generated by Diagra, ReportLab Commercial drawing editor  
# It took only few clicks to generate the code.
from reportlab.lib.colors import Color, blue, red
from reportlab.graphics.charts.legends import Legend, TotalAnnotator
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin
from standard_colors import pdf_chart_colors, setItems
from reportlab.lib.validators import Auto
from reportlab.graphics.charts.barcharts import VerticalBarChart

class FactSheetHoldingsVBar(_DrawingEditorMixin,Drawing):
    def __init__(self,width=400,height=200,*args,**kw):
        apply(Drawing.__init__,(self,width,height)+args,kw)
        self._add(self,VerticalBarChart(),name='bar',validate=None,desc=None)
        self.bar.data             = [[4.22], [4.12], [3.65], [3.56], [3.49], [3.44], [3.07], [2.84], [2.76], [1.09]]
        self.bar.categoryAxis.categoryNames = ['Financials','Energy','Health Care','Telecoms','Consumer','Consumer 2','Industrials','Materials','Other','Liquid Assets']
        self.bar.categoryAxis.labels.fillColor = None
        self.bar.width                      = 200
        self.bar.height                     = 150
        self.bar.x                          = 30
        self.bar.y                          = 15
        self.bar.barSpacing                 = 5
        self.bar.groupSpacing               = 5
        self.bar.valueAxis.labels.fontName  = 'Helvetica'
        self.bar.valueAxis.labels.fontSize  = 8
        self.bar.valueAxis.forceZero        = 1
        self.bar.valueAxis.rangeRound       = 'both'
        self.bar.valueAxis.valueMax         = None#10#
        self.bar.categoryAxis.visible       = 1
        self.bar.categoryAxis.visibleTicks  = 0
        self.bar.barLabels.fontSize         = 6
        self.bar.valueAxis.labels.fontSize  = 6
        self.bar.strokeWidth                = 0.1
        self.bar.bars.strokeWidth           = 0.5
        n                                   = len(self.bar.data)
        setItems(n,self.bar.bars,'fillColor',pdf_chart_colors)
        #add and set up legend
        self._add(self,Legend(),name='legend',validate=None,desc=None)
        _ = ['Vodafone Group', 'UBS', 'British Petroleum', 'Royal bk of Scotland', 'HSBC Holdings', 'Total Elf Fina', 'Repsol', 'Novartis', 'BNP Paribas', 'Schneider Electric' ]
        self.legend.colorNamePairs  = [(Auto(chart=self.bar),(t,'%.2f'% d[0])) for t,d in zip(_,self.bar.data)]
        self.legend.columnMaximum   = 10
        self.legend.fontName        = 'Helvetica'
        self.legend.fontSize        = 5.5
        self.legend.boxAnchor       = 'w'
        self.legend.x               = 260
        self.legend.y               = self.height/2
        self.legend.dx              = 8
        self.legend.dy              = 8
        self.legend.alignment       = 'right'
        self.legend.yGap            = 0
        self.legend.deltay          = 11
        self.legend.dividerLines    = 1|2|4
        self.legend.subCols.rpad    = 10
        self.legend.dxTextSpace     = 5
        self.legend.strokeWidth     = 0
        self.legend.dividerOffsY    = 6
        self.legend.colEndCallout   = TotalAnnotator(rText='%.2f'%sum([x[0] for x in self.bar.data]), fontName='Helvetica-Bold', fontSize=self.legend.fontSize*1.1)
        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))]

if __name__=="__main__": #NORUNTESTS
    drawing = FactSheetHoldingsVBar()
    drawing.save(formats=['pdf'],outDir='.',fnRoot=None)
    drawing.save(formats=['png'],outDir='.',fnRoot=None)


User comments

gravatar smishra June 8, 2011
Hi, While running this code, I am facing an error on line from standard_colors import pdf_chart_colors, setItems stating that: Import Error: No module named standard_colors I dont understand whether there is a problem while installing reportlab or some thg else. Please guide.
gravatar Fer Aug. 1, 2011
You should include this in your code: from reportlab.lib.colors import HexColor pdf_chart_colors = [ HexColor("#0000e5"), HexColor("#1f1feb"), HexColor("#5757f0"), HexColor("#8f8ff5"), HexColor("#c7c7fa"), HexColor("#f5c2c2"), HexColor("#eb8585"), HexColor("#e04747"), HexColor("#d60a0a"), HexColor("#cc0000"), HexColor("#ff0000"), ] def setItems(n, obj, attr, values): m = len(values) i = m // n for j in xrange(n): setattr(obj[j],attr,values[j*i % m]) It should work now :)

Post a comment...

You must log in before you can post comments.