4

I need to produce a chart with consisting of both of line plot and bar plot using python-pptx. Based on documentation, it was stated that

"Most charts only have a single plot and python-pptx doesn’t yet support creating multi-plot charts, but you can access multiple plots on a chart that already has them."

http://python-pptx.readthedocs.io/en/latest/user/charts.html

Does it still hold true? Are there workarounds? I mostly prefer to automate chart creation using chart placeholder in a template rather than pre-creating the charts in template and only update values afterwards. The first approach is more consistent with all other PowerPoint automation I currently have.

idazuwaika
  • 2,749
  • 7
  • 38
  • 46

1 Answers1

5

Creating so-called "multi-plot" charts in python-pptx is not yet supported at the API level. So if you wanted to do it, you would have to write your own code for that part.

However the internals of python-pptx can provide a lot of support, including providing full access once you've added an additional plot.

A full recipe would extend beyond this Q&A format, but here's the general gist.

  • The PowerPoint presentation is essentially a big XML hierarchy. The general strategy is to find your way to the right parent element, then use the best means available to add the right child XML hierarchy (representing a new plot) to that parent element.

  • So you want to start by discovering what a multi-plot XML hierarchy looks like in the neighborhood of interest. opc-diag is helpful for this. Create a single-slide presentation with a chart having two plots, maybe line and bar. Use opc-diag to dump the chart1.xml part and search for the lineChart and barChart elements. If you start with a line chart, your job will be to add the barChart element you find there. So now you can see your objective clearly.

  • You use python-pptx to get that parent element. In this case I believe it's c:plotArea element. You can get that at chart.plots._plotArea. This will be a subclass of BaseOxmlElement which is itself a subclass of _Element from lxml. So all those operations are then at your disposal. If you search around on 'python-pptx workaround function' you'll find some examples. Just a quick handy tip here, you can dump the XML for any element object using its .xml property. This can be very helpful for tracking your progress as you learn the XML manipulation calls.

  • Then you build up your new child element and add it onto the parent in the right place, probably using .append(), possible .insert(). Another approach might be to add a dummy bar chart, find it's c:barChart element, do a deepcopy() and append that. That would be a lot less work on the internals if it works.

Anyway, hope that gives you an idea. As you can probably tell it's not for the faint of heart, but plenty of folks who had the Python chops have been able to get what they need with this approach.

scanny
  • 26,423
  • 5
  • 54
  • 80