2

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?

asdfkjasdfjk
  • 3,784
  • 18
  • 64
  • 104

2 Answers2

7

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.

scanny
  • 26,423
  • 5
  • 54
  • 80
  • Nice but how do we edit the axis titles of a chart which is already present in my ppt file from an embedded excel sheet? you can find more info here - https://stackoverflow.com/questions/72949464/python-ppt-find-and-replace-within-a-chart – The Great Jul 12 '22 at 10:21
0

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.
saafan
  • 1
  • 1