How to change/add chart data series in python-pptx?

本秂侑毒 提交于 2019-12-11 12:29:45

问题


I'm trying to set data in an existing chart using python-pptx.

from pptx import Presentation
pres_path = "C:\\pres.pptx"
pres = Presentation(pres_path)

pres.slides[3].shapes[4].chart.series[0].values

(92.0, 330.0, 309.0, 313.0, 356.0, 421.0, 457.0)

pres.slides[3].shapes[4].chart.series[0].values = (1,2,3)

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  AttributeError: can't set attribute

There's a method mentioned in the documentation which seems relevant, but I can't understand how to use it: http://python-pptx.readthedocs.org/en/latest/_modules/pptx/chart/data.html

pres.slides[3].shapes[4].chart.replace_data((1,2,3))


Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Python27\lib\site-packages\pptx\chart\chart.py", line 119, in     replace_data
    _SeriesRewriter.replace_series_data(self._chartSpace, chart_data)
  File "C:\Python27\lib\site-packages\pptx\chart\chart.py", line 197, in replace_series_data
sers = cls._adjust_ser_count(chartSpace, len(chart_data.series))
AttributeError: 'tuple' object has no attribute 'series'

I'd appreciate any help you can provide. Thanks!


回答1:


To add a new series to an existing table behind a chart you need to do 3 things:

  1. create an instance of ChartData()
  2. provide category name
  3. add the new series to the ChartData() object, using the "add_series()" func.

    chart_data = ChartData()
    chart_data.categories = 'category_name'
    
    for col_idx, col in enumerate(single_df.columns):
        chart_data.add_series(col, (single_df.ix[:, col_idx].values))            
    
    shp.chart.replace_data(chart_data)
    


来源:https://stackoverflow.com/questions/30821917/how-to-change-add-chart-data-series-in-python-pptx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!