How to quickly make prettier figures with Matplotlib
A lot of us use matplotlib for making plots & figures. This article contains simple tips & tricks for making prettier figures - especially when copy&pasting them for presentations. This is about easy suggestions (low effort, high impact), not perfectionising your figures!
(Though I am happy to talk about how to improve the looks of your figures further…!)
Also check out the extensive matplotlib tutorials and examples gallery :-)
The following code snippets assume you ran
import matplotlib
import matplotlib.pyplot as pltMake figure contents more legible
Increase resolution to avoid blurriness
Increase dots-per-inch from the default of 100 to e.g. 200:
matplotlib.rcParams["figure.dpi"] = 200
(or pass dpi=200 argument to plt.figure() / plt.subplots()…)
Increase font size
Especially for presentations:
matplotlib.rcParams["font.size"] = 18
Read more: Customizing Matplotlib with style sheets and rcParams
Share axes when using subplots
Pass sharex=True and/or sharey=True to plt.subplots():
fig, axes = plt.subplots(num_rows, num_cols, sharex=True, sharey=True)
This automatically removes the extra tick labels that usually just get in the way, and ensures each subplot has the same axis limits.
Read more: Customizing Figure Layouts Using GridSpec and Other Functions
Use tight_layout to optimize spacing
Simply call
plt.tight_layout()
as the last line in your plotting code!
Read more: Tight Layout guide
Use LaTeX-style maths
Do use LaTeX for axis labels, legends, titles: simply enclose within $, e.g.
plt.xlabel(r"$ \log \sigma(x_2) $")
The r before the "" saves you from having to escape all the backslashes.
Read more: Writing mathematical expressions
Use appropriate colours
Use “Cn” to obtain consistent colours based on the current color cycle, e.g.
plt.plot(x, y, color="C3")
plt.plot(x[0], y[0], "o", color="C3")
to ensure they match.
Read more on colors:
Use Seaborn
Seaborn builds on top of matplotlib to provide better out-of-the-box data visualization for common tasks (see example gallery). While Seaborn is an additional dependency, it does provide good defaults for plotting, and you can make use of its features even if you stick to custom matplotlib code for your plots.
The following assumes you also ran
import seabornAutomatically adjust scaling of plot elements for different contexts
seaborn.set_context("talk") # or "paper" or "poster"; default: "notebook"
Despine your axes
By default, this removes the top and right spines of an axis object:
seaborn.despine(ax=axis)
Read more on using Seaborn to improve aesthetics:
Optimized color palettes
Read more on the color palettes provided by Seaborn: