简体   繁体   English

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

[英]Change Chart Background Color with python-pptx

I am trying to change the background color of an existing Powerpoint chart with python-pptx.我正在尝试使用 python-pptx 更改现有 Powerpoint 图表的背景颜色。 However, the 'fill' attribute doesn't seem to be implemented for charts yet.但是,似乎还没有为图表实现“填充”属性。 What I've tried so far:到目前为止我已经尝试过:

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)

I've also tried to edit the fill attribute of the chart_frame and the plot, but it doesn't work.我也尝试编辑 chart_frame 和 plot 的填充属性,但它不起作用。

Is there any workaround function to manipulate the underlying xml in order to solve this problem?是否有任何解决方法 function 来操纵底层 xml 以解决此问题?

Any help is much appreciated!任何帮助深表感谢!

Found the answer on my own in the meantime:与此同时,我自己找到了答案:

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)

This changes the color to background color 2 (bg2).这会将颜色更改为背景颜色 2 (bg2)。 In order to change it to a RGBColor, exchange the CT_SchemaColor object with a CT_sRGBColor object and update it accordingly with a hex color code:要将其更改为 RGBColor,请将 CT_SchemaColor object 与 CT_sRGBColor object 交换,并使用十六进制颜色代码进行相应更新:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM