import numpy as np
import polars as pl
from plotnine import (
ggplot, aes,
geom_bar, geom_path, geom_point,
coord_polar,
scale_x_discrete, scale_y_continuous,
theme,
)
from plotnine.data import mtcars2 Examples from the ggplot2 documentation
The following examples are adapted from the ggplot2 book’s coord chapter.
All of the examples on this page require the coord-polar branch of iangow/plotnine. The standard version of plotnine does not include the coord_polar() and coord_radial() functions used here.
The source code for this repository can be found here and includes a pyproject.toml file that can be used with uv to install everything needed to run all the examples here.
2.1 Bar → Pie → Bullseye (mtcars)
A stacked bar chart becomes a pie chart when theta = "y" maps height (count) to angle, and a bullseye chart when the default theta = "x" maps the discrete x position to angle instead.
mtcars_pl = (
pl.from_pandas(mtcars)
.with_columns(
pl.lit("1").alias("x"),
pl.col("cyl").cast(pl.Utf8),
)
)(
ggplot(mtcars_pl, aes(x="x", fill="cyl"))
+ geom_bar(width=1)
+ scale_x_discrete(expand=(0, 0))
+ scale_y_continuous(expand=(0, 0))
+ theme(legend_position="none", figure_size=(4, 4))
)
(
ggplot(mtcars_pl, aes(x="x", fill="cyl"))
+ geom_bar(width=1)
+ coord_polar(theta="y")
+ scale_x_discrete(expand=(0, 0))
+ scale_y_continuous(expand=(0, 0))
+ theme(legend_position="none", figure_size=(4, 4))
)
(
ggplot(mtcars_pl, aes(x="x", fill="cyl"))
+ geom_bar(width=1)
+ coord_polar()
+ scale_x_discrete(expand=(0, 0))
+ scale_y_continuous(expand=(0, 0))
+ theme(legend_position="none", figure_size=(4, 4))
)
2.2 Polar path (spiral)
In ggplot2 a straight line in Cartesian space becomes a spiral in polar coordinates. theta = "x" maps the x-column (here: angle in radians) to the angular axis; y maps to radius.
n = 100
spiral = pl.DataFrame({
"r": np.linspace(0, 1, n),
"theta": np.linspace(0, 3 / 2 * np.pi, n),
})
(
ggplot(spiral, aes(x="theta", y="r"))
+ geom_path()
+ geom_point(size=2, color="red")
+ coord_polar()
+ theme(figure_size=(5, 5))
)