使用 python-pptx 更改图表背景颜色

Change Chart Background Color with python-pptx

我正在尝试使用 python-pptx 更改现有 Powerpoint 图表的背景颜色。但是,'fill' 属性似乎还没有为图表实现。到目前为止我尝试了什么:

chart_frame = shapes.add_chart(chart_type, left, top, width, height, chart_data)
chart = chart_frame.chart
chart.fill.solid()
chart.fill.fore_color.rgb = RGBColor(r, g, b)

我也试过编辑 chart_frame 和情节的填充属性,但它不起作用。

是否有任何变通函数来操纵底层 xml 以解决此问题?

非常感谢任何帮助!

同时自己找到了答案:

from pptx.oxml.xmlchemy import OxmlElement

chart_frame = shapes.add_chart(chart_type, left, top, width, height, chart_data)
chart = chart_frame.chart

shape_properties = OxmlElement("c:spPr")
chart.element.append(shape_properties)
fill_properties = OxmlElement("a:solidFill")
shape_properties.append(fill_properties)
scheme_color = OxmlElement("a:schemeClr")
color_value = dict(val="bg2")
scheme_color.attrib.update(color_value)
fill_properties.append(scheme_color)

这会将颜色更改为背景色 2 (bg2)。为了将其更改为 RGBColor,将 CT_SchemaColor 对象与 CT_sRGBColor 对象交换,并使用十六进制颜色代码相应地更新它:

rgb_color = OxmlElement("a:srgbClr")
color_value = dict(val='%02x%02x%02x' % (130, 130, 130))
rgb_color.attrib.update(color_value)
fill_properties.append(rgb_color)