sevatster sevatster - 4 months ago 35
Python Question

Python pptx custom color for each category

I'm looking at example here:
https://python-pptx.readthedocs.org/en/latest/user/charts.html?highlight=color#pie-chart

chart_data = ChartData()
chart_data.categories = ['West', 'East', 'North', 'South', 'Other']
chart_data.add_series('Series 1', (0.135, 0.324, 0.180, 0.235, 0.126))

chart = slide.shapes.add_chart(
XL_CHART_TYPE.PIE, x, y, cx, cy, chart_data
).chart

chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False

chart.plots[0].has_data_labels = True
data_labels = chart.plots[0].data_labels
data_labels.number_format = '0%'
data_labels.position = XL_LABEL_POSITION.OUTSIDE_END


But I can't understand how to make each category with custom not automatic color:
west is yellow, east is blue, north is grey, south is red, other as brown for example.

Answer

Custom coloring on a series is accomplished using the .fill attribute on the series.

Unfortunately that attribute hasn't been implemented yet for pie charts, only for bar and column charts. http://python-pptx.readthedocs.org/en/latest/api/chart.html#barseries-objects

It is possible to change the default coloring though, in the "template" .pptx file you start with, which accomplishes the same thing for many folks. All the charts in the file will have the same coloring, but it doesn't have to be the built-in defaults.