Search code examples
pythongraphreportlab

fill the slices with different colors on a pie chart


I have a pie chart with 6 slices, and I am looking forward to change the default colors that appear in the pie chart. As far as I found , using the .fillColor I can change the color of a slice.

pie_chart = Drawing(200, 200)
pc = Pie()
pc.x = 65
pc.y = 15
pc.width = 150
pc.height = 150
pc.data = [65,13,12,9,1]
pc.labels = ['Name','Another','Yet Another','Test','Stack','Flow')

We can change the color of a slice using:
pc.slices[1].fillColor=red

However I am looking forward to change the color of all 6 slices and therefore I tried:

colores=[red,brown,violet,yellow,green,pink]
pc.slices.fillColors=colores

And it outputs the error:

AttributeError: Illegal attribute 'fillColors' in class WedgeProperties

My question is : How can I change the color of each slice in a single line of code? Is there any property to do so?


Solution

  • There is no attribute fillColors: it's singular, fillColor; you can't simply change the name and expect the parser to figure out what you mean.

    As TemporalWolf already led you toward, the documentation shows how to do this with a loop. In your case, something like:

    for index, color in enumerate(colores):
        pc.slices[i].fillColor  = colores[i]
    

    This assumes that you have len(colores) slices in your chart.