Brennan Tolman
Brennan Tolman

Reputation: 43

pptx Chart class arguments

I'm trying to call the Chart class in the pptx module. Chart has two arguments: chartSpace and chart_part. The problem is that I have no idea what those two arguments are. There is probably a simple answer to this, but I've tried looking over all the documentation and can't find anything about these arguments. Can someone explain what these arguments are looking for?

from pptx import Presentation
from pptx.enum.chart import XL_CHART_TYPE, XL_TICK_LABEL_POSITION
from pptx.chart.data import CategoryChartData
from pptx.chart.data import ChartData
from pptx.enum.shapes import PP_PLACEHOLDER
from pandas import DataFrame as DF
from pptx.chart.chart import Chart

prs_dir = 'Directory'

layout = prs.slide_layouts[6]
slide = prs.slides.add_slide( layout )

chart_data = ChartData()
chart_data.categories = ['Budget','Actuals']
chart_data.add_series('Budget', (1,21,23,4,5,6,7,35))
chart_data.add_series('Actuals', (1,21,23,4,5,6,7,35))

chart = Chart()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-207-e560d7744421> in <module>
----> 1 chart = Chart()

TypeError: __init__() missing 2 required positional arguments: 'chartSpace' and 'chart_part'```





Upvotes: 1

Views: 223

Answers (1)

scanny
scanny

Reputation: 28933

The Chart class is not intended to be instantiated directly. Use the .add_chart() method on the slide shapes collection to add a chart.

from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches

# create presentation with 1 slide ------
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])

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

# add chart to slide --------------------
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
slide.shapes.add_chart(
    XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
)

prs.save('chart-01.pptx')

More details are available in the documentation here: https://python-pptx.readthedocs.io/en/latest/user/charts.html

Upvotes: 2

Related Questions