Python-pptx:更新或更改现有图表数据

asd*_*fjk 3 python-pptx

我打开一个 pptx 文件并想要更改图表数据集。我怎样才能做到这一点?

prs = Presentation("mypresentation.pptx")
chart = prs.slides[0].shapes[2].chart
Run Code Online (Sandbox Code Playgroud)

我从幻灯片中得到了上面的图表。我不想改变图表的样式或任何内容。想保持原样。只是想更改数据集值。我怎样才能做到这一点?

sca*_*nny 8

python-pptx可以使用该方法更改提供 PowerPoint 图表中显示的值的数据Chart.replace_data()
https://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.chart.Chart.replace_data

ChartData创建一个新对象来保存新数据,然后将该对象传递给该.replace_data()方法:

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)
Run Code Online (Sandbox Code Playgroud)

请注意,对于 XY/散点图或气泡图,此过程略有不同,因为这些图表类型使用不同的图表数据对象。