Plotnine Tutorial: ggplot2 Style Charts in Python

Make your first Plotnine chart, understand data, aesthetics and geoms, and find the tutorial for bars, facets, labels, themes and saving.

Plotnine brings R's ggplot2 grammar to Python. Start with ggplot(df, aes("x", "y")), then add layers with +, such as geom_point() for a scatter plot or geom_col() for bars. This tutorial uses Plotnine 0.15; install it with pip install plotnine or uv add plotnine.

Grid of six Plotnine charts: labeled bars, grouped bars, facets, an annotated chart, built-in themes and faceted scatter plots

Quick Example

Dough height over three hours for three kinds of flour, with one color per flour.

import numpy as np
import pandas as pd
from plotnine import (aes, geom_line, geom_point, ggplot, labs,
                      scale_color_manual, theme, theme_minimal)

# Sample data: dough height measured every 20 minutes.
rng = np.random.default_rng(61)
minutes = np.arange(0, 181, 20)
frames = []
for flour, peak, speed in [("White", 11.5, 38), ("Whole wheat", 9.0, 48), ("Rye", 7.2, 60)]:
    height = 4 + (peak - 4) * (1 - np.exp(-minutes / speed)) + rng.normal(0, 0.15, len(minutes))
    frames.append(pd.DataFrame({"flour": flour, "minutes": minutes, "height_cm": height}))
dough = pd.concat(frames, ignore_index=True)

chart = (
    ggplot(dough, aes("minutes", "height_cm", color="flour"))
    + geom_line(size=1)
    + geom_point(size=2.5)
    + scale_color_manual(values={"White": "#e09f3e", "Whole wheat": "#9e2a2b", "Rye": "#335c67"})
    + labs(title="How fast does the dough rise?", x="Minutes", y="Height (cm)", color="Flour")
    + theme_minimal()
    + theme(figure_size=(7, 4.5))
)
chart

Plotnine line chart of dough height over 180 minutes; white flour rises highest, then whole wheat, then rye

The parentheses let each layer sit on its own line. In a notebook, ending the cell with chart displays it; in a script, call chart.show() or chart.save("dough.png").

How Does the Grammar of Graphics Work?

A Plotnine chart is a stack of parts. Only the data, the aesthetics and one geom are needed; the rest have defaults.

Part Example What it does
Data ggplot(dough, ...) A pandas or Polars DataFrame
Aesthetics aes("minutes", "height_cm", color="flour") Maps columns to position, color, size or shape
Geom geom_line() Draws the data
Scale scale_color_manual(...) Controls colors, axis ticks and limits
Facet facet_wrap("flour") Splits the chart into panels
Labels labs(title=...) Sets titles and axis and legend names
Theme theme_minimal() Styles everything that isn't data

A value inside aes() comes from the data, so aes(color="flour") gives each flour its own color. A value passed to the geom is a constant: geom_line(color="gray") makes every line gray.

Which Geom Should I Use?

Chart Geom
Scatter plot geom_point()
Line chart geom_line()
Bars from values geom_col()
Bars from row counts geom_bar()
Histogram geom_histogram(binwidth=...)
Box plot or violin plot geom_boxplot(), geom_violin()
Trend line geom_smooth(method="lm")
Heatmap geom_tile(aes(fill=...))
Text on the chart geom_text(aes(label=...))

Which Plotnine Tutorial Do I Need?

You want to Tutorial
Draw a first scatter plot with a trend line An Intro to Plotnine
Make sorted, grouped or stacked bars Plotnine Bar Charts
Split a chart into panels Faceted Plots
Set titles, format axes and annotate Titles and Labels
Change the theme Custom Themes
Export PNG, SVG or PDF Save a Plot
Convert R code ggplot2 to Plotnine

Common Plotnine Problems

Problem Fix Details
IndentationError or TypeError when a line starts with + Wrap the whole expression in parentheses Translation guide
NameError for a column name Quote it: aes("minutes", "height_cm") Translation guide
geom_bar() raises KeyError: 'x' when given only y Map categories to x and add coord_flip() for horizontal bars Bar charts
Bars disappear after setting ylim Bars start at zero; zoom with coord_cartesian(ylim=...) Bar charts
theme() settings have no effect Put them after complete themes such as theme_minimal() Themes
dpi is ignored after calling .draw() Save a fresh copy of the plot, such as (chart + theme()) Saving

Plotnine, Seaborn or Matplotlib?

Plotnine is a good fit if you already know ggplot2, or you like building charts by adding layers. Seaborn covers common statistical charts with one function call each, and Matplotlib gives control over every element. Plotnine draws with Matplotlib, so you can call .draw() to get a Matplotlib figure and edit it.

Similar Topics