Make PowerPoint Charts in Python with python-pptx

Add native, editable charts to a PowerPoint file with python-pptx: slide.shapes.add_chart(), chart data, formatting, Matplotlib images, updating existing charts and building a deck in a loop.

To add a chart to a PowerPoint slide in Python, build a CategoryChartData object and pass it to slide.shapes.add_chart() from python-pptx. The result is a real PowerPoint chart, not a picture: anyone who opens the file can right-click it, choose Edit Data and restyle it. When you need a chart PowerPoint cannot draw, such as a histogram or a heatmap, draw it with Matplotlib and insert the image instead.

This post was run with python-pptx 1.0.2 and Matplotlib 3.11. Install the library with pip install python-pptx (the import name is pptx). The slide images below are previews rendered on a Mac with Quick Look, so PowerPoint itself will draw fonts and spacing a little differently.

Quick Example

The data is simulated quarterly revenue for three sales regions (seeded, so you get the same numbers). The new_slide() helper is reused in every later section, and it is the only part that depends on the blank template.

import numpy as np
from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION
from pptx.enum.text import PP_ALIGN
from pptx.util import Inches, Pt

rng = np.random.default_rng(8)
quarters = ["Q1", "Q2", "Q3", "Q4"]
regions = ["North", "South", "West"]
revenue = {r: (rng.uniform(80, 120) * np.cumprod(1 + rng.normal(0.04, 0.05, 4))).round(0)
           for r in regions}

prs = Presentation()
prs.slide_width, prs.slide_height = Inches(13.333), Inches(7.5)  # the default template is 4:3


def new_slide(prs, text):
    slide = prs.slides.add_slide(prs.slide_layouts[5])  # layout 5 is "Title Only"
    title = slide.shapes.title
    title.left, title.top, title.width, title.height = Inches(0.8), Inches(0.4), Inches(11.7), Inches(1.0)
    title.text = text
    para = title.text_frame.paragraphs[0]
    para.alignment, para.font.size, para.font.bold = PP_ALIGN.LEFT, Pt(30), True
    return slide


slide = new_slide(prs, "Revenue by region ($k)")

data = CategoryChartData()
data.categories = quarters
for region in regions:
    data.add_series(region, revenue[region])

frame = slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED,
                               Inches(0.8), Inches(1.6), Inches(11.7), Inches(5.4), data)
chart = frame.chart
chart.font.size = Pt(14)
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False
chart.value_axis.minimum_scale, chart.value_axis.maximum_scale = 0, 140
chart.plots[0].has_data_labels = True

prs.save("revenue.pptx")

PowerPoint slide titled Revenue by region with a clustered column chart of North, South and West revenue for four quarters, with data labels

add_chart() takes the chart type, the position and size of the chart (left, top, width, height) and the data, and returns a graphic frame. The chart itself is frame.chart. In this data South grows from 95 to 124 over the year while North slips from 91 to 83, so the Q4 bars show North well below the other two.

Three details are easy to miss. The default template is 4:3, so set prs.slide_width and prs.slide_height for a widescreen deck. prs.slide_layouts[5] is "Title Only" in that default template (a custom template numbers its layouts differently). And prs.save() is the only thing that writes a file, so nothing appears until you call it.

What chart types can python-pptx make?

XL_CHART_TYPE lists dozens of types. The ones you will use most are COLUMN_CLUSTERED, COLUMN_STACKED, BAR_CLUSTERED, LINE_MARKERS, AREA, PIE, DOUGHNUT and XY_SCATTER. Bar, line, area and pie charts take CategoryChartData. Scatter charts take XyChartData, which needs an x and a y for every point. The same data object can feed several charts, so this slide draws four chart types from the data built in the Quick Example:

slide = new_slide(prs, "Four chart types, one data object")
w, h = Inches(5.9), Inches(2.85)

specs = [  # chart type, left, top, axis maximum (None lets PowerPoint choose)
    (XL_CHART_TYPE.LINE_MARKERS, Inches(0.5), Inches(1.5), 140),
    (XL_CHART_TYPE.COLUMN_STACKED, Inches(6.9), Inches(1.5), None),
    (XL_CHART_TYPE.BAR_CLUSTERED, Inches(0.5), Inches(4.4), 140),
    (XL_CHART_TYPE.COLUMN_STACKED_100, Inches(6.9), Inches(4.4), None),
]
for kind, left, top, top_value in specs:
    chart = slide.shapes.add_chart(kind, left, top, w, h, data).chart
    if top_value:
        chart.value_axis.minimum_scale, chart.value_axis.maximum_scale = 0, top_value

PowerPoint slide with four small charts of the same data: a line chart with markers, a stacked column chart, a horizontal bar chart and a 100 percent stacked column chart

The slide is crowded because each chart is only 2.85 inches tall, so in a real deck give a chart most of the slide. A pie chart uses only the first series, so it needs its own data. A scatter chart needs XyChartData:

from pptx.chart.data import XyChartData

slide = new_slide(prs, "A pie chart and a scatter plot")

pie_data = CategoryChartData()
pie_data.categories = regions
pie_data.add_series("Q4 revenue", [revenue[r][-1] for r in regions])
slide.shapes.add_chart(XL_CHART_TYPE.PIE, Inches(0.5), Inches(1.6), w, Inches(5.2), pie_data)

xy = XyChartData()
points = xy.add_series("Orders")
for items, value in zip(rng.integers(1, 9, 25), rng.uniform(20, 60, 25)):
    points.add_data_point(int(items), float(value * items))
slide.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER, Inches(6.9), Inches(1.6), w, Inches(5.2), xy)

XY_SCATTER draws markers only, with the connecting lines switched off. Use XY_SCATTER_LINES if you want the lines. I left these two charts out of the preview images because Quick Look draws pies and scatter charts differently from PowerPoint, and I didn't want to show a picture that is not what you will see.

How do I format a python-pptx chart?

Everything you would click in PowerPoint is a property on the chart. Fills live on series.format.fill, the axes are chart.value_axis and chart.category_axis, and number formats use Excel format strings. Setting number_format_is_linked = False is what makes a custom format stick:

from pptx.dml.color import RGBColor

slide = new_slide(prs, "Revenue by region, stacked")
chart = slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_STACKED,
                               Inches(0.8), Inches(1.6), Inches(11.7), Inches(5.4), data).chart
chart.font.size = Pt(14)
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False

for series, color in zip(chart.series, ["264653", "2A9D8F", "E9C46A"]):
    series.format.fill.solid()
    series.format.fill.fore_color.rgb = RGBColor.from_string(color)

chart.plots[0].gap_width = 60  # percent of a bar's width left between columns
axis = chart.value_axis
axis.has_title = True
axis.axis_title.text_frame.text = "Revenue ($k)"
axis.tick_labels.number_format = '"$"#,##0"k"'
axis.tick_labels.number_format_is_linked = False
axis.major_gridlines.format.line.color.rgb = RGBColor(0xDD, 0xDD, 0xDD)
chart.category_axis.format.line.color.rgb = RGBColor(0x88, 0x88, 0x88)

PowerPoint slide with a stacked column chart in dark teal, green and yellow for North, South and West, with narrow gaps between the columns

The hex strings go through RGBColor.from_string(), which wants six characters without a #. If you need a color from your company palette, this is where it goes. Fonts are set the same way, on chart.font for the whole chart or on a part such as axis.tick_labels.font.

The preview above shows the colors and the gap width, but Quick Look ignores axis titles and custom number formats. PowerPoint shows the "Revenue ($k)" title and labels such as $200k, and the XML python-pptx writes does contain both.

How do I put a Matplotlib chart on a slide?

PowerPoint cannot draw a histogram, a heatmap or most statistical charts as a native chart. For those, save the Matplotlib figure into an in-memory PNG and add it with slide.shapes.add_picture(). Pass only a width and the height follows the image's aspect ratio:

import io
import matplotlib.pyplot as plt

orders = rng.lognormal(4.2, 0.5, 500)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(orders, bins=30, color="#2A9D8F", edgecolor="white")
ax.axvline(np.median(orders), color="#264653", linestyle="--", label=f"Median ${np.median(orders):.0f}")
ax.set_xlabel("Order value ($)")
ax.set_ylabel("Orders")
ax.legend()

buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=200, bbox_inches="tight")
plt.close(fig)

slide = new_slide(prs, "Order values are right-skewed")
slide.shapes.add_picture(buf, Inches(1.87), Inches(1.6), width=Inches(9.6))
prs.save("report.pptx")

PowerPoint slide titled Order values are right-skewed with a Matplotlib histogram of 500 order values and a dashed median line

dpi=200 keeps the picture sharp on a projector. The trade-off is that a picture can't be edited in PowerPoint. If the numbers change you have to rerun the script, which is usually what you want for a report built from code anyway.

How do I update a chart in an existing presentation?

Open the file with Presentation("file.pptx"), find the shape with shape.has_chart, and call chart.replace_data() with a new CategoryChartData. The formatting stays and only the numbers change, which makes it a good way to refresh a monthly deck built from a template:

prs2 = Presentation("revenue.pptx")
chart = next(shape.chart for shape in prs2.slides[0].shapes if shape.has_chart)

restated = CategoryChartData()
restated.categories = quarters
for region in regions:
    restated.add_series(region, (revenue[region] * 1.05).round(0))
chart.replace_data(restated)

prs2.save("revenue-updated.pptx")
print(len(prs2.slides), "slide,", len(list(chart.plots[0].series)), "series")
1 slide, 3 series

The revenue column chart after replace_data, with every bar about 5 percent taller and the axis, legend and colors unchanged

The axis maximum is the 140 we set in the Quick Example, so a series that grows past it would be clipped. Remove the explicit scale (or raise it) when the new data could be larger. Charts are found by shape.has_chart, not by name, so give yourself a way to tell them apart (the slide index, or shape.name) when a slide holds several.

How do I build a deck from a loop?

A deck is just add_slide() in a for loop. Here each region gets its own slide with a one-series chart and speaker notes:

deck = Presentation()
deck.slide_width, deck.slide_height = Inches(13.333), Inches(7.5)

for region in regions:
    slide = new_slide(deck, f"{region}: quarterly revenue ($k)")
    region_data = CategoryChartData()
    region_data.categories = quarters
    region_data.add_series(region, revenue[region])
    slide.shapes.add_chart(XL_CHART_TYPE.COLUMN_CLUSTERED,
                           Inches(0.8), Inches(1.6), Inches(11.7), Inches(5.4), region_data)
    change = revenue[region][-1] / revenue[region][0] - 1
    slide.notes_slide.notes_text_frame.text = f"{region} revenue changed {change:+.0%} from Q1 to Q4."

deck.save("by-region.pptx")
print(len(deck.slides), "slides")
3 slides

The same loop works for one slide per product, per month or per customer. Read the table with pandas, group by the column that decides the slides, and add one chart per group.

python-pptx vs images vs exporting from a BI tool

Native chart (add_chart) Matplotlib picture (add_picture)
Editable in PowerPoint Yes, with Edit Data No
Chart types Bar, line, pie, area, scatter, a few more Anything Matplotlib draws
Look Follows the PowerPoint theme Exactly what you drew
File size Small One PNG per chart
Best for Charts the audience will tweak Histograms, heatmaps, annotated charts

Pick native charts for simple business charts that colleagues might edit, and pictures for anything the chart types above cannot draw. The two mix freely on one slide. To save the same figures as a PDF instead, see How to Generate PDF Data Reports with Embedded Python Charts.

Practical Tips

  • Start from your company template. Presentation("template.pptx") keeps its theme, fonts and layouts. Print [l.name for l in prs.slide_layouts] to find the layout you want instead of guessing an index.
  • Set the slide size only on a new deck. The 16:9 change in this post is for the blank default. A template already has its own size, so changing it would stretch the layouts.
  • Charts inherit the theme fonts and colors. If a native chart looks off, fix it in the template's theme before overriding every series in code.
  • python-pptx writes .pptx only. It can't open the older .ppt format, and it can't render slides to images. Use PowerPoint or LibreOffice to export a deck to PDF.
  • Keep the data in a DataFrame. Build CategoryChartData from df.index and df[col] with a short loop, so a changed table re-creates the chart with no other edits.

Similar Topics