import datetime
import numpy as np
import pandas as pd
from mizani.labels import label_custom
from plotnine import (
ggplot,
aes,
geom_violin,
geom_sina,
labs,
coord_flip,
scale_x_discrete,
scale_y_continuous,
scale_fill_gradient,
element_text,
element_line,
element_rect,
element_blank,
theme )
Temperature over the Year
ridgeline
density plot
Create the data
1234)
np.random.seed(= [10, 11, 14, 18, 23, 26, 29, 32, 25 ,18, 14, 6]
averages = [3, 3, 4, 6, 7, 8, 5, 5, 4, 7, 4, 3]
sd = [datetime.date(2022, 1, 1) + datetime.timedelta(days=i) for i in range(365)]
date
= pd.DataFrame({
data "date": date,
"month": [f"{d:%B}" for d in date],
"temperature": [
round(np.random.normal(averages[d.month-1], sd[d.month-1]))
for d in date
]
})= data["month"].unique().tolist()[::-1]
months "month"] = data["month"].astype(pd.CategoricalDtype(categories=months))
data["mean_temperature"] = data.groupby("month", observed=True)["temperature"].transform("mean")
data[
data.head()
date | month | temperature | mean_temperature | |
---|---|---|---|---|
0 | 2022-01-01 | January | 11 | 9.967742 |
1 | 2022-01-02 | January | 6 | 9.967742 |
2 | 2022-01-03 | January | 14 | 9.967742 |
3 | 2022-01-04 | January | 9 | 9.967742 |
4 | 2022-01-05 | January | 8 | 9.967742 |
To achieve the ridgeline effect, we create right sided violin
and sina
plots, with both geoms set to an equivalent width
/ maxwidth
. We then flip the coordinate system for a vertical layout and theme the plot for a better look.
= "#D2D2D2"
line_color = 0.25
line_size
("month", "temperature", fill="mean_temperature"))
ggplot(data, aes(+ geom_violin(
="identity",
position="right",
style=2,
width="none",
color=line_size,
size=False,
trim=.85,
alpha
)+ geom_sina(
="identity",
position="right",
style="#AAAAAA",
fill=1,
size=0,
stroke=2,
maxwidth=123
random_state
)+ labs(title="Temperature over the Year")
+ scale_y_continuous(
=(0, 0.5),
expand=label_custom("{:.0f}°C")
labels
)+ scale_x_discrete(expand=(0, -.95, 0, 0))
+ scale_fill_gradient("#2222BB", "#AA2222")
+ coord_flip()
+ theme(
=(6, 6),
figure_size="none",
legend_position=element_text(color="#222222"),
text=element_line(size=line_size, color=line_color),
line=element_blank(),
axis_line=element_line(linetype=(0, (20, 20))),
panel_grid_major_x=element_blank(),
panel_grid_minor=element_blank(),
axis_ticks_minor=50,
axis_ticks_length_major_y=element_blank(),
axis_title=element_text(va="bottom", ha="left", margin={"t": 5, "r": -45}),
axis_text_y=element_text(ha="left", margin={"t": -7}),
axis_text_x=12,
axis_ticks_length=element_rect(fill="#FAFAFA"),
panel_background=element_blank(),
panel_border
) )