Search code examples
pythonpowerpointpython-pptx

Change Chart Background Color with python-pptx


I am trying to change the background color of an existing Powerpoint chart with python-pptx. 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.

Is there any workaround function to manipulate the underlying xml in order to solve this problem?

Any help is much appreciated!


Solution

  • 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). 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:

    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)