Plotnine Titles and Labels: labs(), Axis Formatting, and Annotations

Set titles, subtitles, captions, axis labels, and legend titles in Plotnine, then format tick labels, align and style the text, and add annotations.

Use labs() to set every title and label in Plotnine: title, subtitle, caption, x, y, and the legend title, which is named after its aesthetic (color, fill, shape). Position and font settings go in theme(). The examples use plotnine 0.15.

Quick Example

import numpy as np
import pandas as pd
from mizani.labels import label_comma
from plotnine import (aes, geom_line, geom_point, ggplot, labs,
                      scale_color_manual, scale_x_date, scale_y_continuous,
                      theme, theme_minimal)

rng = np.random.default_rng(43)
months = pd.date_range("2025-01-01", periods=12, freq="MS")
season = np.sin((np.arange(12) - 2.5) / 12 * 2 * np.pi)
visits = pd.DataFrame({
    "month": list(months) * 2,
    "museum": ["Science"] * 12 + ["Art"] * 12,
    "visitors": np.concatenate([
        14000 + 5200 * season + rng.normal(0, 600, 12),
        9000 + 2100 * season + rng.normal(0, 500, 12),
    ]).round(),
})

base = (
    ggplot(visits, aes("month", "visitors", color="museum"))
    + geom_line(size=1)
    + geom_point(size=2.5)
    + theme_minimal()
    + theme(figure_size=(7, 4.5))
)
colors = {"Science": "#6a4c93", "Art": "#ff7f11"}
color_scale = scale_color_manual(values=colors)
month_axis = scale_x_date(date_breaks="2 months", date_labels="%b")
count_axis = scale_y_continuous(labels=label_comma())
text = labs(
    title="Science museum visits swing with the seasons",
    subtitle="Monthly visitors, 2025",
    caption="Source: made-up admissions data",
    x="",
    y="Visitors",
    color="Museum",
)

chart = base + color_scale + month_axis + count_axis + text
chart

Plotnine line chart of monthly visitors in 2025 for a science and an art museum, with a title, subtitle, caption, and legend titled Museum

What can labs() set?

Argument What it labels
title headline above the chart
subtitle second line under the title
caption note at the bottom, usually the data source
tag panel letter such as "A"
x, y axis titles
color, fill, shape, size, linetype legend title for that aesthetic

ggtitle("..."), xlab("..."), and ylab("...") are shortcuts for single labels. Break long text with \n. An empty string, as in x="", removes an axis title that the tick labels already explain.

Align and Style the Title

Plotnine centers a title that stands alone. When there is also a subtitle, both are left-aligned with the plot area, as in the chart above. Set ha in element_text() to override this (ha="center", for example), and use plot_title_position="plot" to align with the edge of the figure. Each piece of text has its own theme setting.

from plotnine import element_text

left = chart + theme(
    plot_title_position="plot",
    plot_caption_position="plot",
    plot_title=element_text(ha="left", size=16, weight="bold", color="#22223b"),
    plot_subtitle=element_text(ha="left", size=11, color="#555555",
                               margin={"b": 12}),
    plot_caption=element_text(ha="left", size=8, style="italic", color="#777777"),
    axis_title_y=element_text(size=10, color="#555555"),
    legend_title=element_text(weight="bold"),
)
left

The same chart with a large bold left-aligned title, gray subtitle, and italic caption at the lower left

The default, plot_title_position="panel", lines text up with the plot area. margin adds space around text, in points.

How do I format axis tick labels in Plotnine?

Pass a formatter to the labels argument of the axis scale. The mizani package, installed with plotnine, has the common ones.

Formatter Input Output
label_comma() 25000 25,000
label_currency(precision=0, big_mark=",") 25000 $25,000
label_percent() 0.25 25%
label_number(scale=1/1000, suffix="k", accuracy=1) 25000 25k

Any function that takes a list of values and returns a list of strings also works. Date axes use scale_x_date() with a strftime pattern in date_labels.

from mizani.labels import label_number
from plotnine import element_blank

ticks = (
    base
    + color_scale
    + scale_x_date(date_breaks="1 month",
                   date_labels="%b %Y", expand=(0.02, 0))
    + scale_y_continuous(labels=label_number(scale=1 / 1000, suffix="k",
                                             accuracy=1))
    + theme(axis_text_x=element_text(rotation=45, ha="right"),
            panel_grid_minor=element_blank())
    + labs(title="Shorter numbers, rotated dates", x="", y="Visitors",
           color="Museum")
)
ticks

The museum chart with y ticks written as 5k to 20k and month and year labels rotated 45 degrees on the x axis

Set each scale once per chart. Adding a second one for the same axis replaces the first, and Plotnine warns you about it.

Rename, Move, or Hide the Legend

The labels argument of a manual scale renames legend entries. guides() controls the legend's layout, and theme(legend_position=...) places it.

from plotnine import guide_legend, guides

legend = (
    base + month_axis + count_axis + text
    + scale_color_manual(
        values=colors,
        labels={"Science": "Science Center", "Art": "Art Museum"},
    )
    + guides(color=guide_legend(title="", nrow=1))
    + theme(legend_position="top")
)
legend

The museum chart with an untitled legend above the plot reading Art Museum and Science Center

To put the legend inside the plot, use legend_position="inside" with legend_position_inside=(0.85, 0.85). legend_position="none" hides it.

Annotate Points on the Chart

annotate() places a single piece of text or a shape in data coordinates. geom_text() labels rows of a DataFrame, which is what you want for "label the last point of each line".

from plotnine import annotate, geom_text

peak = visits.loc[visits["visitors"].idxmax()]
ends = visits[visits["month"] == visits["month"].max()]

annotated = (
    base + color_scale + count_axis + text
    + annotate("text", x=peak["month"], y=peak["visitors"] + 1100,
               label=f"Peak: {peak['visitors']:,.0f}", size=9, color="#6a4c93")
    + geom_text(aes(label="museum"), data=ends, ha="left",
                nudge_x=8, size=9, show_legend=False)
    + scale_x_date(date_breaks="2 months", date_labels="%b",
                   limits=(months[0], pd.Timestamp("2026-01-20")))
    + theme(legend_position="none")
)
annotated

The museum chart with the science museum's peak month labeled with its visitor count and each line named at its right end instead of a legend

Text alignment on a geom uses ha and va. R's hjust and vjust raise an error as geom_text() arguments. Wrap math in dollar signs, as in labs(y="$R^2$"), to typeset it with Matplotlib's mathtext.

Practical Tips

  • Write the title as the finding ("visits swing with the seasons") and put the measure and period in the subtitle.
  • Style text once in a theme object and add it to every chart.
  • A complete theme such as theme_minimal() resets earlier theme() settings, so add it first.
  • Direct labels need extra room on the axis. Extend limits so they aren't dropped.

Similar Topics