How to add a custom font in plotnine
Plotnine is a package that brings the grammar of graphics, similar to {ggplot2} in R, to Python.
Like {ggplot2}, plotnine supports the use of custom fonts. To add a custom font:
1import matplotlib.font_manager as fm
import os
2project_dir = os.getcwd()
font_path = os.path.join(project_dir, "Raleway-VariableFont_wght.ttf")
prop = fm.FontProperties(fname=font_path)
p = (
ggplot(rates_long, aes(x="date", y="rate", color="type"))
+ geom_line()
+ theme(
3 title=element_text(hjust=0, fontproperties=prop),
text=element_text(fontproperties=prop),
plot_background=element_rect(fill="white")
)
)- 1
-
Install
matplotlib’s font_manager. - 2
-
Install the custom font on your system, and use the
ospackage to point to the directory with your custom font. - 3
-
Set the font in your
plotnineplot using thetheme()function.
I posted a plotnine plot on Reddit using the Raleway font (code here):