每个类别的Python pptx自定义颜色

时间:2015-12-14 10:29:10

标签: python python-pptx

我在这里看例子: 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

但我无法理解如何使用自定义而非自动颜色制作每个类别: 西部为黄色,东部为蓝色,北部为灰色,南部为红色,其他为棕色。例如。

3 个答案:

答案 0 :(得分:2)

我在Github上回答了这个问题,现在可以修改饼图的颜色。

由于饼图只是多个点的一个序列,因此您需要分别修改每个点。可以通过遍历第一个意甲的每个点(因为这是饼图中唯一的一个点)并根据需要更改颜色来实现。点颜色位于.format.fill参数中,您可以使用上面提供的链接scanny轻松进行交互。

以下是您的用例的简单代码段:

        # [yellow, blue, grey, red, brown]
        color_list = ["ffff00", "0000ff", "D3D3D3", "ff0000", "A52A2A"]
        # Go through every point of the first serie and modify the color
        for idx, point in enumerate(chart.series[0].points):
            col_idx = idx % len(color_list)
            point.format.fill.solid()
            point.format.fill.fore_color.rgb = RGBColor.from_string(color_list[col_idx])

干杯!

答案 1 :(得分:1)

可以更改折线图中的线条颜色,因为我尝试了很多建议,但没有成功,例如以下代码:

            _green = RGBColor(156, 213, 91)
            plot = chart.plots[0]
            series = plot.series[0]
            line = series.format.line
            line.fill.rgb = _green 

答案 2 :(得分:0)

系列中的自定义着色是使用系列中的.fill属性完成的。

不幸的是,对于饼图,该属性尚未实现,仅适用于条形图和柱形图。 http://python-pptx.readthedocs.org/en/latest/api/chart.html#barseries-objects

可以在"模板"中更改默认颜色。你开始使用.pptx文件,它为许多人完成同样的事情。文件中的所有图表都具有相同的颜色,但它不必是内置的默认值。