Geoms and Positions

This page groups extra layers by display task: dense points, categorical points, labels, margins, and low-ink summaries.

[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()

Point density and connected points

geom_pointdensity() colors points by local density. geom_pointpath() draws points and a matching path from one layer.

[2]:
iris_small = iris.copy()

(
    ggplot(iris_small, aes("sepal_length", "petal_length"))
    + geom_pointdensity(size=2.3)
    + theme_scientific()
    + labs(x="Sepal length", y="Petal length")
)

/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/pandas/util/_decorators.py:219: FutureWarning: After 0.17 or January 2028, whichever comes first, the default behavior will switch to using an entropy initialized numpy.random.Generator.
[2]:
../_images/vignettes_geoms-and-positions_3_1.png
[3]:
path_data = flights[flights["year"].isin([1949, 1950])].copy()
path_data["month_index"] = path_data.groupby("year").cumcount() + 1

(
    ggplot(path_data, aes("month_index", "passengers", color="factor(year)"))
    + geom_pointpath(linesize=0.7)
    + scale_color_tableau(k=2)
    + theme_few()
    + labs(x="Month", y="Passengers", color="Year")
)

[3]:
../_images/vignettes_geoms-and-positions_4_0.png

Categorical point placement

geom_beeswarm() and geom_quasirandom() separate overlapping points while preserving the categorical axis.

[4]:
(
    ggplot(tooth, aes("dose", "len", color="supp"))
    + geom_boxplot(alpha=0.25, outlier_shape=None)
    + geom_beeswarm(size=2.1, cex=1.6)
    + scale_color_colorblind(k=2)
    + theme_classic2()
    + labs(x="Dose", y="Tooth length", color="Supplement")
)

[4]:
../_images/vignettes_geoms-and-positions_6_0.png
[5]:
(
    ggplot(tooth, aes("dose", "len", fill="supp"))
    + geom_half_violin(alpha=0.55, side="l")
    + geom_half_boxplot(width=0.18, side="r")
    + geom_quasirandom(aes(color="supp"), width=0.12, size=1.8)
    + scale_fill_tableau(k=2)
    + scale_color_tableau(k=2)
    + theme_clean()
    + labs(x="Dose", y="Tooth length")
)

[5]:
../_images/vignettes_geoms-and-positions_7_0.png

Labels and callouts

The text layers handle repelled labels, boxed labels, and a small subset of markdown-style formatting.

[6]:
label_data = penguin_data.groupby("species", observed=True).tail(2).copy()

(
    ggplot(penguin_data, aes("bill_length_mm", "bill_depth_mm", color="species"))
    + geom_point(alpha=0.55)
    + geom_text_repel(aes(label="species"), data=label_data, show_legend=False)
    + scale_color_few(k=3)
    + theme_few()
)

[6]:
../_images/vignettes_geoms-and-positions_9_0.png
[7]:
notes = pd.DataFrame({
    "x": [35, 55],
    "y": [21, 13],
    "label": ["**Deep bills**<br>Adelie-rich region", "Longer bills\nGentoo and Chinstrap"],
})

(
    ggplot(penguin_data, aes("bill_length_mm", "bill_depth_mm"))
    + geom_point(alpha=0.35)
    + geom_richtext(aes("x", "y", label="label"), data=notes, inherit_aes=False)
    + geom_textbox(
        aes(x="x", y="y - 1.8", label="label"),
        data=notes,
        inherit_aes=False,
        text_width=18,
        fill="#f7f7f7",
    )
    + theme_pubclean()
)

[7]:
../_images/vignettes_geoms-and-positions_10_0.png

Margins, raster-like polygons, and Tufte summaries

Use margin geoms when a rectangle should extend to a panel edge. Use the Tufte geoms when the summary should use fewer marks than a standard boxplot.

[8]:
raster_data = pd.DataFrame({
    "x": np.repeat(np.arange(5), 5),
    "y": np.tile(np.arange(5), 5),
})
raster_data["z"] = np.sin(raster_data["x"]) + np.cos(raster_data["y"])

(
    ggplot(raster_data, aes("x", "y", fill="z"))
    + geom_polygonraster()
    + theme_clean()
    + labs(x="Column", y="Row", fill="Value")
)

[8]:
../_images/vignettes_geoms-and-positions_12_0.png
[9]:
(
    ggplot(tooth, aes("dose", "len"))
    + geom_tufteboxplot()
    + geom_rangeframe()
    + theme_tufte()
    + labs(x="Dose", y="Tooth length")
)

/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/plotnine/stats/stat.py:358: UserWarning:
The following aesthetics were dropped during processing: ['y'].
plotnine could not infer the correct grouping.
Did you forget to specify a `group` aesthetic or to convert a numerical variable into a categorial?

[9]:
../_images/vignettes_geoms-and-positions_13_1.png

position_lineartrans() and position_disjoint_ranges() are lower-level position adjustments. They are intended for custom layers that need a simple coordinate transform or automatic packing of interval rows.