1

I added a chart in docx, and I hope I can edit the data to change histogram bins length.

How can I do it?

enter image description here

@scanny This is the code I tried, and show me error is

chart.replace_data(chart_data) AttributeError: 'module' object has no attribute 'replace_data'

import docx
import os
import sys
import csv
import datetime
import time
import pptx
from pptx import chart
from pptx.chart import data
from pptx.chart.data import CategoryChartData

CURRENT_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))

docxFilePath = os.path.join(CURRENT_DIR,'sample.docx')


chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))

chart.replace_data(chart_data)

filename ='test.docx'
filepath = os.path.join(r'C:\Users\Administrator\Desktop\python test\update_test', filename)

doc.save(filepath)
panda001
  • 109
  • 1
  • 3
  • 12

1 Answers1

1

Charts in python-pptx are updated by populating a new ChartData object and passing it to chart.replace_data:

from pptx.chart.data import CategoryChartData

chart_data = CategoryChartData()
chart_data.categories = ['East', 'West', 'Midwest']
chart_data.add_series('Series 1', (19.2, 21.4, 16.7))

chart.replace_data(chart_data)
scanny
  • 26,423
  • 5
  • 54
  • 80
  • Thanks reply I tried the code,but it says name chart not defined. So I wondering is that possible I can use docx to modify the word excel table for the histogram? – panda001 Nov 08 '17 at 21:00
  • Show the code you used and the exact error text that resulted. – scanny Nov 09 '17 at 00:38
  • Nice solution. But when I try the same for excel, I don't see any updates being made in chart axis labels. Is this something that you will be interested to look at? I have put a bounty on this question - https://stackoverflow.com/questions/72949464/python-ppt-find-and-replace-within-a-chart – The Great Jul 15 '22 at 02:18