Skip to main content

Data analysis · Intermediate · 18 min

Build charts layer by layer with plotnine

By Padding · Updated 18 Nov 2026
Python 3.15.2 · plotnine 0.15.9 · pandas 3.1.1 · uv 0.13 (checked on python:3.15-slim)

You will build a faceted delivery-times chart in plotnine 0.15 from data, aesthetics and layers, give it scales, labels and a theme, and save it as a PNG and an SVG you have checked.

On this page

Most Python charting libraries give you a function per chart type: call bar() for bars, scatter() for a scatter plot. plotnine works differently. It is a Python implementation of the grammar of graphics, the system behind R's ggplot2, and you describe a chart as parts added together: a table of data, a mapping from columns to visual properties (the aesthetics), one or more layers of marks (the geoms), and then optional facets, scales and a theme. Change one part and the others keep working, so a scatter plot becomes a faceted scatter plot with trend lines by adding two lines, not by starting again.

In this tutorial you chart a small, made-up set of 24 deliveries by motorbike and van in Accra, Kigali, Lagos and Nairobi. You start with bare points, then map vehicle to colour and shape, add trend lines and a label, split the chart into one panel per city, tidy the scales and theme, and save a PNG and an SVG.

If you already write ggplot2 in R, most of what you know carries across. The differences are small and come up as you go: column names are strings, a multi-line chart sits inside parentheses, and ggsave() is the .save() method. If you want ready-made statistical charts in one call instead, seaborn is the better fit; plotnine is for when you want to compose the chart yourself.

A stack of seven labelled bars, from ggplot with data, through aes, geom_point, geom_smooth, facet_wrap and scale_x_continuous, to theme_bw and labs, beside a sketch of two city panels with points, trend lines and an 88 min label
Each + adds one part of the grammar; the finished chart is their sum.

Step 1 · Set up the project and the delivery data

Make a throwaway folder, start a uv project and add plotnine and pandas, pinned so your output matches this page. plotnine brings matplotlib, mizani (its scales library) and statsmodels (used for trend lines) with it:

Bash
mkdir -p ~/plotnine-demo
cd ~/plotnine-demo
uv init --no-package --python 3.15
uv add "plotnine==0.15.9" "pandas==3.1.1"
uv run python -c "import plotnine; print('plotnine', plotnine.__version__)"

The install pulls in NumPy, SciPy, matplotlib and statsmodels, which take up a few hundred megabytes once unpacked and a large download to match. On prepaid mobile data, run it once on Wi-Fi; uv keeps a cache, so later projects that pin the same versions install from disk.

Now write the data. Each row is one delivery: the city, the vehicle, the distance in kilometres and the time it took in minutes. The figures are illustrative, not measurements:

Bash
cd ~/plotnine-demo
cat > deliveries.csv <<'CSV'
city,vehicle,distance_km,minutes
Accra,motorbike,2.4,14
Accra,motorbike,4.9,24
Accra,motorbike,8.7,39
Accra,van,3.3,22
Accra,van,6.8,40
Accra,van,11.4,64
Kigali,motorbike,1.5,9
Kigali,motorbike,3.8,17
Kigali,motorbike,7.2,30
Kigali,van,2.2,15
Kigali,van,5.6,29
Kigali,van,9.9,47
Lagos,motorbike,2.1,18
Lagos,motorbike,5.4,31
Lagos,motorbike,9.8,52
Lagos,van,3.0,29
Lagos,van,7.5,55
Lagos,van,12.2,88
Nairobi,motorbike,1.8,12
Nairobi,motorbike,6.0,27
Nairobi,motorbike,10.5,44
Nairobi,van,2.5,20
Nairobi,van,8.1,46
Nairobi,van,13.0,71
CSV
wc -l deliveries.csv

The data is already tidy, one row per observation and one column per variable. That is the shape plotnine expects. If yours has one column per city or per month, reshape it to long form first, as in reshape data with pivot and melt.

Check it worked

The first command ends with plotnine 0.15.9. wc -l reports 25 lines: a header and 24 deliveries.

Step 2 · Draw the first chart from data, aesthetics and one geom

Every plotnine chart starts with ggplot(data, aes(...)). aes() maps columns to aesthetics, here distance to the x position and minutes to the y position. That alone draws an empty pair of axes, because nothing says what marks to make. Adding geom_point() gives it a layer of points:

Bash
cd ~/plotnine-demo
cat > first.py <<'PY'
import pandas as pd
from plotnine import aes, geom_point, ggplot

deliveries = pd.read_csv("deliveries.csv")

plot = ggplot(deliveries, aes(x="distance_km", y="minutes")) + geom_point()
plot.save("01-points.png", width=6, height=4, dpi=100, verbose=False)
print("saved 01-points.png")
PY
uv run first.py

Two things differ from R. Column names are strings ("distance_km", not a bare distance_km), because Python would otherwise look for a variable of that name. And there is no ggsave() call at the end: the chart object has a .save() method that takes the file name, the size in inches and the resolution. verbose=False stops it printing the size it chose.

In a Jupyter notebook you can leave plot as the last line of a cell and it renders inline, which is quicker while you are exploring.

Check it worked

The script prints saved 01-points.png. Open the file: 24 black points rise from bottom left to top right, with distance_km on the x axis and minutes on the y axis, on plotnine's default grey panel.

Step 3 · Map a column to colour and shape, and set fixed values outside aes

Add color="vehicle" and shape="vehicle" to the mapping, and plotnine gives each vehicle its own colour and marker, picks them from its default scales and draws a legend. Arguments you pass to the geom itself, outside aes(), are fixed values for every mark: here a size of 3 and 80% opacity.

Bash
cd ~/plotnine-demo
cat > mapped.py <<'PY'
import pandas as pd
from plotnine import aes, geom_point, ggplot

deliveries = pd.read_csv("deliveries.csv")

plot = (
    ggplot(deliveries, aes(x="distance_km", y="minutes", color="vehicle", shape="vehicle"))
    + geom_point(size=3, alpha=0.8)
)
plot.save("02-mapped.png", width=6, height=4, dpi=100, verbose=False)
print("saved 02-mapped.png")

try:
    broken = ggplot(deliveries, aes(x="distance_km", y="minutes", color="black")) + geom_point()
    broken.draw()
except Exception as error:
    print(type(error).__name__ + ":", str(error).splitlines()[0])
PY
uv run mapped.py

The parentheses around the chart let you put each + part on its own line, which is how R users write ggplot2. Without them, Python would end the statement at the first line break.

The second half of the script shows the most common mistake. aes(color="black") is a mapping, so plotnine reads "black" as an expression to evaluate against the data, finds no column called black, and stops. In R the same code quietly gives you a legend with one entry called "black"; plotnine fails loudly instead. To make every point black, write geom_point(color="black").

Two panels side by side. Left, mapped: aes(color="vehicle") sends the motorbike and van values through a scale to two colours, with a legend. Right, set: geom_point(color="black", size=3) makes every point the same black with no legend, and a note that aes(color="black") looks for a column called black and raises an error
Inside aes() a string names a column; outside, it is a value.

Check it worked

The script prints saved 02-mapped.png, then a line starting PlotnineError: that names the color mapping and 'black'. In 02-mapped.png, motorbikes are round and vans are triangles in a second colour, and a legend titled vehicle sits on the right.

Step 4 · Add layers for trend lines and a label

A layer is a geom plus the statistic it draws. geom_point() draws the data as it is; geom_smooth(method="lm") fits a straight line to each group with statsmodels and draws that. Because color="vehicle" sits in the top-level aes(), every layer inherits it, so you get one line per vehicle. shape only means something to points, so it moves into the point layer's own aes().

Each layer can also take its own data. The label layer below gets a one-row table holding the slowest delivery, so it writes a single label instead of 24:

Bash
cd ~/plotnine-demo
cat > layers.py <<'PY'
import pandas as pd
from plotnine import aes, geom_point, geom_smooth, geom_text, ggplot, labs

deliveries = pd.read_csv("deliveries.csv")
slowest = deliveries.nlargest(1, "minutes")

plot = (
    ggplot(deliveries, aes(x="distance_km", y="minutes", color="vehicle"))
    + geom_point(aes(shape="vehicle"), size=3)
    + geom_smooth(method="lm", se=False)
    + geom_text(
        aes(label="minutes"),
        data=slowest,
        format_string="{} min",
        nudge_x=-1.2,
        color="black",
        size=9,
    )
    + labs(
        title="Vans take longer per kilometre",
        x="Distance (km)",
        y="Delivery time (minutes)",
        color="Vehicle",
        shape="Vehicle",
        caption="Illustrative data: 24 deliveries in four cities",
    )
)
plot.save("03-layers.png", width=7, height=4.5, dpi=100, verbose=False)
print("layers:", len(plot.layers))
row = slowest.iloc[0]
print("slowest:", row["city"], row["vehicle"], row["minutes"])
PY
uv run layers.py

se=False hides the shaded confidence band. With six points per vehicle the band is wide enough to cover most of the chart; leave it on when you want to show how uncertain a fit is. labs() names the axes and the legend; giving color and shape the same title merges their two legends into one.

Check it worked

The script prints layers: 3 and slowest: Lagos van 88. In 03-layers.png, a straight line runs through each vehicle's points, the van line is steeper, the top-right point reads 88 min, and the legend is titled Vehicle.

Step 5 · Split the chart into one panel per city with facet_wrap

Pooled together, four cities hide each other. facet_wrap("city") draws the same layers once per city, each panel holding only that city's rows, on shared axes so the panels compare fairly. ncol=2 arranges them in a two-by-two grid. R users can also write facet_wrap("~city"); both forms work.

To count the panels, this script calls .draw(), which returns the underlying matplotlib figure, and counts its axes:

Bash
cd ~/plotnine-demo
cat > facets.py <<'PY'
import pandas as pd
from plotnine import aes, facet_wrap, geom_point, geom_smooth, ggplot, labs

deliveries = pd.read_csv("deliveries.csv")

plot = (
    ggplot(deliveries, aes(x="distance_km", y="minutes", color="vehicle"))
    + geom_point(aes(shape="vehicle"), size=2.5)
    + geom_smooth(method="lm", se=False)
    + facet_wrap("city", ncol=2)
    + labs(x="Distance (km)", y="Delivery time (minutes)", color="Vehicle", shape="Vehicle")
)
figure = plot.draw()
print("panels:", len(figure.axes))
figure.savefig("04-facets.png", dpi=100)
PY
uv run facets.py

Because the y axis is shared, Lagos's slow vans stand out at once against Kigali's. If you set scales="free_y", each panel gets its own range, which shows the shape within a city better but makes panels easy to misread side by side; keep shared scales unless you say so in the title.

Check it worked

The script prints panels: 4. 04-facets.png shows four panels headed Accra, Kigali, Lagos and Nairobi in alphabetical order, each with its own pair of trend lines, and only the left column has y-axis labels.

Step 6 · Control the scales, labels and theme

Scales turn data values into what you see: positions, tick labels, colours and shapes. Every aesthetic has a default scale, and you replace it by adding your own. Themes control everything that is not data: background, grid lines, fonts and the size of the figure. Write the finished chart as chart.py:

Bash
cd ~/plotnine-demo
cat > chart.py <<'PY'
import pandas as pd
from plotnine import (
    aes,
    element_blank,
    element_text,
    facet_wrap,
    geom_point,
    geom_smooth,
    geom_text,
    ggplot,
    labs,
    scale_color_manual,
    scale_shape_manual,
    scale_x_continuous,
    scale_y_continuous,
    theme,
    theme_bw,
)

deliveries = pd.read_csv("deliveries.csv")
slowest = deliveries.nlargest(1, "minutes")

vehicle_colours = {"motorbike": "#1b6ca8", "van": "#d1495b"}
vehicle_shapes = {"motorbike": "o", "van": "s"}

chart = (
    ggplot(deliveries, aes(x="distance_km", y="minutes", color="vehicle"))
    + geom_point(aes(shape="vehicle"), size=2.5)
    + geom_smooth(method="lm", se=False, size=0.8)
    + geom_text(
        aes(label="minutes"),
        data=slowest,
        format_string="{} min",
        nudge_x=-2.2,
        color="black",
        size=9,
    )
    + facet_wrap("city", ncol=2)
    + scale_x_continuous(breaks=[0, 5, 10, 15], limits=(0, 15))
    + scale_y_continuous(breaks=range(0, 100, 20), labels=lambda ys: [f"{y:.0f} min" for y in ys])
    + scale_color_manual(values=vehicle_colours)
    + scale_shape_manual(values=vehicle_shapes)
    + labs(
        title="Vans take longer per kilometre in every city",
        x="Distance (km)",
        color="Vehicle",
        shape="Vehicle",
        caption="Illustrative data: 24 deliveries in four cities",
    )
    + theme_bw(base_size=11)
    + theme(
        figure_size=(8, 5),
        legend_position="top",
        axis_title_y=element_blank(),
        plot_title=element_text(weight="bold"),
    )
)

if __name__ == "__main__":
    figure = chart.draw()
    print("panels:", len(figure.axes))
    print("x ticks:", [int(t) for t in figure.axes[0].get_xticks()])
PY
uv run chart.py

What each addition does:

  • scale_x_continuous fixes the ticks at 0, 5, 10 and 15 km and starts the axis at zero, so distances read as distances.
  • scale_y_continuous puts the unit in each tick label (20 min), so axis_title_y=element_blank() in the theme can remove the y-axis title and give the panels more room.
  • scale_color_manual and scale_shape_manual take a dictionary from data value to colour or marker, so motorbikes are always blue circles and vans always red squares, whatever order the data comes in. The blue and red differ in lightness as well as hue, and the shapes differ too, so the chart still reads in greyscale or for readers with red-green colour blindness.
  • theme_bw() swaps the grey panel for white with a thin border, and theme() then adjusts single elements: the figure size in inches, the legend at the top, no y-axis title, a bold title. element_blank() removes an element; element_text() styles one.

The if __name__ == "__main__": guard means the checks only run when you run chart.py itself, so the next step can import chart without drawing it twice.

Check it worked

The script prints panels: 4 and x ticks: [0, 5, 10, 15]. Nothing is saved yet; that is the next step.

Step 7 · Save the chart as PNG and SVG and check the files

Save two versions: a PNG at 150 dots per inch for slides, chat apps and documents, and an SVG for the web, which stays sharp at any zoom and can be edited in a vector tool. When the theme sets figure_size, .save() uses it, so 8 by 5 inches at 150 dpi gives a PNG 1200 by 750 pixels:

Bash
cd ~/plotnine-demo
cat > save.py <<'PY'
from pathlib import Path

from PIL import Image

from chart import chart

chart.save("delivery-times.png", dpi=150, verbose=False)
chart.save("delivery-times.svg", verbose=False)

for name in ["delivery-times.png", "delivery-times.svg"]:
    print(f"{name}: {Path(name).stat().st_size / 1024:.0f} KB")

with Image.open("delivery-times.png") as image:
    print("png pixels:", image.size)

svg = Path("delivery-times.svg").read_text()
print("svg starts with:", svg.lstrip()[:5])
PY
uv run save.py
ls ~/plotnine-demo/*.png ~/plotnine-demo/*.svg

Pillow, which reads the PNG's size here, is already installed as a matplotlib dependency.

File size matters to the people who open your chart. Many readers across Africa and elsewhere view reports on low-end Android phones over prepaid data, and a 1200-pixel PNG is plenty for a phone screen. Check the sizes the script prints before you send a chart into a group chat or embed it in a page. Here the SVG comes out larger than the PNG, because matplotlib writes every glyph of text as a path; with thousands of points it grows further. Send the PNG to phones and keep the SVG for pages and print.

When you publish the chart, write alt text that states what it shows, for example "Four panels, one per city: delivery time rises with distance, and vans take longer than motorbikes everywhere, most in Lagos, where a 12 km van delivery took 88 minutes."

Check it worked

The script prints two file sizes, something like 70 KB for the PNG and 90 KB for the SVG, then png pixels: (1200, 750) and svg starts with: <?xml. ls lists delivery-times.png and delivery-times.svg beside the four practice PNGs. Open the PNG: four white panels with blue circles and red squares, the legend across the top, tick labels in minutes, and 88 min beside the top-right point in the Lagos panel.

When you have finished, remove the demo folder with rm -rf ~/plotnine-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.