1
votes

I open a pptx file and want to change the chart dataset. How can I do that?

prs = Presentation("mypresentation.pptx")
chart = prs.slides[0].shapes[2].chart

I get the chart as above from the slide. I don't want to change the style or any thing of the chart. Want to keep as it is. Just want to change the dataset values. How can I do that?

2

2 Answers

4
votes

The data providing the values displayed in a PowerPoint chart can be changed with python-pptx using the Chart.replace_data() method.
https://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.chart.Chart.replace_data

A new ChartData object is created to hold the new data, then that object is passed to the .replace_data() method:

from pptx.chart.data import CategoryChartData

# ---define new chart data---
chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))

# ---replace chart data---
chart.replace_data(chart_data)

Note that this procedure is slightly different for an XY/Scatter chart or Bubble chart because those chart types use a different chart-data object.

0
votes

To add to scanny's answer, if you want to replace data for XY/Scatter do the following:

  1. Instead of CategoryChartData you have to use XySeriesData and XyChartData
  2. You need to add your data as a x,y (XySeriesData) using XyChartData.add_series() , best approach to do so is by adding each pair individually following this answer https://stackoverflow.com/a/62108452/15523646
  3. If you have more than one series, you can loop through them, and repeat step 2 for each series.
  4. Finally replacing the data is the same as in scanny's answer.