plotnine provides a grammar of graphics implementation for Python. You can build plots by layering components like ggplot, aes (aesthetics), geom_* (geometries), stat_* (statistical transformations), facet_* (faceting), and theme (visual styling) using the + operator.
from plotnine import (
aes,
facet_wrap,
geom_point,
ggplot,
stat_smooth,
theme,
theme_tufte,
theme_xkcd,
)
from plotnine.data import mtcars
# Basic scatter plot with custom theme settings
p1 = (
ggplot(mtcars, aes("wt", "mpg"))
+ geom_point()
+ theme(figure_size=(6, 4), dpi=300)
)
# Adding color aesthetics
p2 = p1 + aes(color="factor(gear")
# Adding a statistical smooth layer (linear model)
p3 = p2 + stat_smooth(method="lm")
# Faceting the plot by a variable
p4 = p3 + facet_wrap("gear")
# Applying specialized themes like xkcd or Tufte
p5 = p4 + theme_xkcd()
p5alt = p4 + theme_tufte()
# Save the plots
p5.save("readme-image-5.png")