Composition and Export Workflows

Use this page after the individual plots are defined. It covers plot layout and figure annotations first, then the related final-stage tasks of plot inspection and animation setup.

[1]:
import numpy as np
import pandas as pd
from plotnine_extra import *
from plotnine_extra.data import ToothGrowth, flights, iris, penguins

tooth = ToothGrowth.assign(dose=ToothGrowth["dose"].astype(str))
penguin_data = penguins.dropna(subset=[
    "bill_length_mm",
    "bill_depth_mm",
    "body_mass_g",
    "species",
]).copy()

Compose plots with operators

| places plots beside each other and / stacks them. plot_layout() sets their relative sizes.

[2]:
base = penguin_data.dropna(subset=["body_mass_g"]).copy()
left = (
    ggplot(base, aes("bill_length_mm", "bill_depth_mm", color="species"))
    + geom_point(alpha=0.65)
    + scale_color_tableau(k=3)
    + theme_few()
)
right = (
    ggplot(base, aes("body_mass_g", fill="species"))
    + geom_density(alpha=0.35)
    + scale_fill_tableau(k=3)
    + theme_few()
)

composition = left | right
composition = composition + plot_layout(widths=[1.6, 1])
composition

[2]:
../_images/vignettes_composition-and-export_3_0.png

Add figure-level annotations

plot_annotation() annotates operator compositions, and ggarrange() / annotate_figure() provide ggpubr-style wrappers for arranging and annotating composed plots. All of it is available on every supported plotnine: plotnine-extra requires plotnine 0.16, so there is no version gating to work around.

[3]:
annotated = composition + plot_annotation(
    title="Penguin morphology",
    caption="Two finished plots arranged with plotnine-extra",
)
annotated

[3]:
../_images/vignettes_composition-and-export_5_0.png
[4]:
arranged = ggarrange(left, right, ncol=2)
arranged = annotate_figure(
    arranged, top="Penguin morphology", bottom="Palmer penguins data"
)
arranged

[4]:
../_images/vignettes_composition-and-export_6_0.png

Query rendered plots

get_breaks() and get_legend() inspect a built plot. get_legend() raises an error when no legend is drawn.

[5]:
axis_plot = (
    ggplot(pd.DataFrame({"x": [1, 2, 3], "y": [2, 3, 5]}), aes("x", "y"))
    + geom_point()
    + scale_x_continuous(breaks=[1, 2, 3])
)
get_breaks(axis_plot, "x")

[5]:
[1, 2, 3]
[6]:
legend_plot = left + guide_stringlegend(title="Species")
legend = get_legend(legend_plot)
type(legend).__name__

[6]:
'FlexibleAnchoredOffsetbox'

Animate plot sequences

PlotnineAnimation takes a sequence of ggplot objects. Save the animation when the runtime has an animation writer such as Pillow or ImageMagick.

[7]:
frames = []
for year in [1950, 1951, 1952]:
    frame_data = flights[flights["year"] == year].copy()
    frame_data["month_index"] = range(1, len(frame_data) + 1)
    frames.append(
        ggplot(frame_data, aes("month_index", "passengers"))
        + geom_line(size=1)
        + geom_point()
        + theme_clean()
        + labs(title=f"Air passengers in {year}", x="Month", y="Passengers")
    )

animation = PlotnineAnimation(frames, interval=300)
type(animation).__name__

[7]:
'PlotnineAnimation'

For static export, use plotnine’s normal save method on an individual plot or on the composed figure.