Search code examples
pythonpython-2.7reportlab

How to set each individual bar in a bar chat to a different color in ReportLab?


I am using this function to create a bar chart using Reportlab

def make_drawing():
    from reportlab.lib import colors
    from reportlab.graphics.shapes import Drawing
    from reportlab.graphics.charts.barcharts import HorizontalBarChart
    drawing = Drawing(400, 200)


    data = [
           (13, 5, 20, 22, 37, 98, 19, 4),
           ]

    names = ["Cat %s" % i for i in xrange(1, len(data[0])+1)]

    bc = HorizontalBarChart()
    bc.x = 20
    bc.y = 50
    bc.height = 200
    bc.width = 400
    bc.data = data
    bc.strokeColor = colors.white
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = -10
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.categoryNames = names

    drawing.add(bc)
    return drawing

By default the bar chart color is set to red

enter image description here

I add these two lines after setting bc.categoryAxis.categoryNames

    bc.bars[0].fillColor = colors.blue
    bc.bars[1].fillColor = colors.red

In the hope to set the first bar to color blue. However all the bars are now in color blue.

enter image description here


Solution

  • Bars charts can have multiple bars at each position like this

    enter image description here

    So, bars is 2 dimensional array. You can set color to individual bars like this

    bc.bars[(0, 0)].fillColor = colors.blue
    bc.bars[(0, 1)].fillColor = colors.green
    

    which will generate chart like this

    enter image description here