Getting started¶
Install¶
pip install ggrust
ggrust works in Jupyter, VS Code notebooks and plain Python scripts. In a notebook, a
plot shows itself when it is the last expression of a cell. In a script, call
plot.show() to open it in the browser, or export it to a file.
Import everything, as with lets-plot:
from ggrust import *
A first plot¶
A plot has three parts: data, a mapping from columns to visual properties (aesthetics), and at least one layer that draws the mapped data.
import polars as pl
from ggrust import *
DATA = "https://raw.githubusercontent.com/datavil/ggrust/main/docs/data/"
homes = pl.read_csv(DATA + "homes.csv")
plot = ggplot(homes, aes(x="area_m2", y="price_k")) + geom_point()
plot
ggplot(homes, ...)sets the data: a polars or pandas DataFrame, a pyarrow table, or a dict of lists or numpy arrays.aes(x="area_m2", y="price_k")maps two columns to the x and y positions.geom_point()adds a layer that draws one point per row.
The parts are joined with +. Each + returns a new plot, so a base plot can be reused.
Mapped and constant aesthetics¶
Inside aes(), an aesthetic follows a column, and a scale and a legend are made for
it. Outside aes(), as a layer argument, it is one constant value for the whole layer.
geom_point(aes(color="neighbourhood")) # one color per neighbourhood, with a legend
geom_point(color="#b7410e") # every point the same color
Labels, a theme and a size¶
Add more pieces with +: labs() for titles and axis names, a theme, and ggsize()
for the size in pixels.
import polars as pl
from ggrust import *
DATA = "https://raw.githubusercontent.com/datavil/ggrust/main/docs/data/"
homes = pl.read_csv(DATA + "homes.csv")
plot = (
ggplot(homes, aes(x="area_m2", y="price_k", color="neighbourhood"))
+ geom_point(size=2, alpha=0.6)
+ labs(
title="Bigger homes cost more, but where matters",
x="Floor area (m²)",
y="Price (thousands)",
color="Neighbourhood",
)
+ theme_classic()
+ ggsize(640, 400)
)
plot
The grammar in one picture¶
Every plot goes through the same steps, as in ggplot2 and lets-plot:
- Data and the mapping pick columns for each aesthetic.
- Each layer's stat summarises the data (
identitykeeps it as is;bin,boxplot,ydensityand others compute new values). - A position adjusts overlapping marks (
stack,dodge,jitter). - Scales turn data values into pixels, colors and sizes, and make axes and legends.
- Facets split the data into panels; a coordinate system places them.
- The theme styles everything that is not data.
The next pages take these one at a time, starting with layers.