Scales and legends¶
A scale turns data values into something visible: a position on an axis, a color, a
size. Every mapped aesthetic has a scale. ggrust picks a default one from the column's
type; add a scale_* to change it.
Discrete colors¶
scale_color_brewer and scale_fill_brewer use the ColorBrewer palettes
("Set1", "Set2", "Dark2", ...). scale_*_manual(values=[...]) takes your own.
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("area_m2", "price_k", color="neighbourhood"))
+ geom_point(size=2.5, alpha=0.7)
+ scale_color_brewer(palette="Set2")
+ labs(x="Floor area (m²)", y="Price (thousands)", color="Neighbourhood")
+ ggsize(640, 400)
)
plot
Continuous colors¶
A numeric column gets a gradient and a colorbar. scale_fill_gradient2 diverges around
a midpoint; scale_*_gradientn takes any list of colors; scale_*_viridis uses the
viridis palettes.
import polars as pl
from ggrust import *
DATA = "https://raw.githubusercontent.com/datavil/ggrust/main/docs/data/"
cities = pl.read_csv(DATA + "cities.csv").with_columns(
label=pl.col("temperature").round(0).cast(pl.Int64)
)
months = cities["month_name"][:12].to_list()
plot = (
ggplot(cities, aes("month_name", "city"))
+ geom_tile(aes(fill="temperature"), color="white", size=0.5)
+ geom_text(aes(label="label"), size=6)
+ scale_x_discrete(limits=months)
+ scale_fill_gradient2(low="#2c7bb6", mid="#ffffbf", high="#d7191c", midpoint=12)
+ labs(x="", y="", fill="°C")
+ theme_minimal()
+ ggsize(700, 300)
)
plot
Position scales¶
scale_x_continuous and scale_y_continuous set breaks, labels, limits and a
format. scale_x_log10, scale_x_log2 and scale_x_reverse (and their y twins) change
the axis itself. Here the x axis is logarithmic and size maps calories:
import polars as pl
from ggrust import *
DATA = "https://raw.githubusercontent.com/datavil/ggrust/main/docs/data/"
fruit = pl.read_csv(DATA + "fruit.csv")
plot = (
ggplot(fruit, aes("sugar_g", "fibre_g"))
+ geom_point(aes(size="calories"), color="#e76f51", alpha=0.7)
+ geom_text_repel(aes(label="fruit"), size=6, seed=3)
+ scale_x_log10()
+ labs(x="Sugar per 100 g (log scale)", y="Fibre per 100 g", size="kcal")
+ theme_bw()
+ ggsize(640, 440)
)
plot
Titles and legends¶
labs() names the plot, the axes and each legend by aesthetic
(labs(color="Neighbourhood")). theme(legend_position=...) moves legends to
"right", "left", "top", "bottom" or hides them with "none"; guides() and
guide_legend() / guide_colorbar() tune a single legend.
All scales are listed in the API reference.