In this post, you'll learn about the different available matplotlib styles that can instantly change the appearance of the plot. Let's begin by making a simple line plot using the default style. This simple style is often the first (and sometimes only) style that many people encounter with matplotlib not realizing how easy it is to choose others.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2, 8, .1)
y = .1 * x ** 3 - x ** 2 + 3 * x + 2
fig, ax = plt.subplots(figsize=(4.5, 3), dpi=100)
ax.plot(x, y)
ax.set_title('Default Matplotlib Style');
There are nearly 30 builtin styles to matplotlib that can be activated with the plt.style.use
function. The style names are available in the plt.style.available
list. In the following code, we iterate through all of the available styles, then make the same line plot as above, setting the style temporarily for each Axes with plt.style.context
.
fig = plt.figure(dpi=100, figsize=(10, 20), tight_layout=True)
available = ['default'] + plt.style.available
for i, style in enumerate(available):
with plt.style.context(style):
ax = fig.add_subplot(10, 3, i + 1)
ax.plot(x, y)
ax.set_title(style)
Each style's settings are stored in the plt.style.library
dictionary. Here, we get all of the settings for the seaborn-darkgrid style.
plt.style.library['seaborn-darkgrid']
To set a style for the current session, do so with plt.style.use
and reset to the default style with plt.style.use('default')
.
If you are interested in completely mastering matplotlib (as well as pandas) so that you can produce trusted results, take a look at the comprehensive book Master Data Analysis with Python. It contains over 800 pages, 500 exercises with detailed solutions, and video lessons.
Upon registration, you'll get access to the following free courses: