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

Python pptx custom color for each category

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

但我不明白如何使每个类别都具有自定义颜色而不是自动颜色: 西黄东蓝北灰南红其他如棕

更新:在原始答案之后的版本中添加了对饼图填充的访问:

这使第一个饼图扇区变红:

from pptx.dml.color import RGBColor

points = pie_chart.plots[0].series[0].points
fill = points[0].format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 0, 0)

为每个额外的所需点重复最后三行,或者可能像这样更花哨的东西来应用主题颜色:

from pptx.enum.dml import MSO_THEME_COLOR

accent_colors = (
    MSO_THEME_COLOR.ACCENT_1,
    MSO_THEME_COLOR.ACCENT_2,
    MSO_THEME_COLOR.ACCENT_3,
    MSO_THEME_COLOR.ACCENT_4,
    MSO_THEME_COLOR.ACCENT_5,
    MSO_THEME_COLOR.ACCENT_6,
)

pie_chart_points = pie_chart.plots[0].series[0].points

for point, accent_color in zip(pie_chart_points, accent_colors):
    fill = point.format.fill
    fill.solid()
    fill.fore_color.theme_color = accent_color

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

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

不过,可以在开始时使用的 "template" .pptx 文件中更改默认颜色,这对许多人来说都是一样的。文件中的所有图表都将具有相同的颜色,但不一定是内置默认值。

可以更改折线图中的线的颜色,因为我尝试了很多建议但没有成功,就像这段代码:

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

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

由于饼图只是一系列的多个点,您需要单独修改每个点。这可以通过遍历第一个 Serie 的每个点(因为它是饼图中唯一的点)并根据需要更改颜色来完成。点颜色在 .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])

干杯!