from plotnine import (
ggplot,
aes,
geom_point,
geom_boxplot,
stat_smooth,
facet_wrap,
labs,
scale_color_manual,
element_text,
element_rect,
element_line,
element_blank,
theme_gray,
theme_set,
theme,
)
from plotnine.data import penguins
= penguins.dropna() penguins
The Plots that Want to be Together
plot composition
theme
smooth
box plot
For a common look & feel, change the default theme that will apply to all plots in the composition.
= "#5B4F41", "#FCF9F4"
c1, c2
theme_set(
theme_gray()+ theme(
=(8, 6),
figure_size=element_text(color=c1),
text="none",
legend_position=element_rect(fill=c2),
panel_background=element_line(color=c1, linetype="dashdot", alpha=0.1),
panel_grid_major=element_blank(),
panel_grid_minor=element_rect(color=c1),
panel_border=element_text(size=8),
axis_text=element_text(color="white"),
strip_text=element_rect(fill=c1, color=c1)
strip_background
)
)
# Use the same scale for the color and fill aesthetics
= scale_color_manual(
scale_color_and_fill =["#DB735C", "#2A91A2", "#F8B75A"],
values=("fill", "color")
aesthetics )
Create the plots and compose them into a single graphic
= (
p1 "bill_depth_mm", "bill_length_mm", color="species"))
ggplot(penguins, aes(+ geom_point(size=0.25)
+ stat_smooth(aes(fill="species"), alpha=0.15)
+ labs(x="Bill Depth (mm)", y="Bill Length (mm)", tag="a)")
+ scale_color_and_fill
)
# We reorder the species along the x-axis so that they match up with the apparent
# order in plot p1
= (
p2 "reorder(species, bill_depth_mm, 'max')", "bill_length_mm", fill="species"))
ggplot(penguins, aes(+ geom_boxplot(size=0.25, outlier_size=0.25)
+ labs(x="Species", y="Bill Length (mm)", tag="b)")
+ scale_color_and_fill
+ theme(axis_title=element_blank())
)
= (
p3
p2+ facet_wrap("sex")
+ labs(tag="c)")
+ theme(axis_title=element_blank())
)
| p2 / p3 p1