Beyond Python Logo

Exploring matplotlib styling and plot colors

Written by Chanse Hungerford
6-minute read (800 words)
Published: Mon Aug 12 2019
Exploring matplotlib's default styling

matplotlib is a powerful plotting package in Python, but the default style settings aren't for everyone. Sometimes you need to modify a plot (or all your plots) to make them look a bit better for a presentation. matplotlib has you covered! There are a lot of built-in styles that you have easy access to.

import matplotlib.pyplot as plt
import numpy as np

# Create a random (normal distribution) dataset
observation_count = 1000
series_count = 5
random_data = np.random.randn(observation_count, series_count)
bucket_count = 10

# Use default styling
plt.hist(random_data, bucket_count);
matplotlib default style
Updating matplotlib's built-in style

Changing the style of a plot is simple and only requires one line of code. Here are a couple of examples.

# Change the current plot style
plt.style.use('fivethirtyeight')
# Data-driven news and analysis: https://fivethirtyeight.com/

plt.hist(random_data, bucket_count, orientation='horizontal');
five thirty eight matplotlib styling
fig = plt.figure(figsize=(14, 6))

# Use context styling to change a single plot
with plt.style.context(('grayscale')):
    ax1 = fig.add_subplot(121)
    ax1.hist(random_data, bucket_count, cumulative=True)
    ax1.set_title('Context Styling')

# The overall style has stayed the same
ax2 = fig.add_subplot(122)
ax2.hist(random_data, bucket_count)
ax2.set_title('Existing Style');
Temporary styles with context
Exploring matplotlib plotting styles

You can see different styles allow you to customize the axes font sizes, tick marker sizes, and the axes labels! How do you know what styles are available? Matplotlib thought of that issue, here's how you print the list of available styles.

print(plt.style.available)

> ['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot',
'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette',
'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted',
'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster',
'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid',
'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']

We're already able to leverage the amazing plotting offerred within matplotlib, often in a single line of code. Now we are able take advantage of thoughtful work others have done with styling. Have you had to consider the needs of a colorblind audience? Researching and building those plots would definitley be a hassle. matplotlib has a builtin style for that, and there are a couple of options!

fig = plt.figure(figsize=(12, 6))
fig.suptitle('Colorblind Styling')

# Style is applied when the subplot is created
# However, if you create multiple subplots at the same
# time then they will have the same styling.
with plt.style.context(('seaborn-colorblind')):
    ax1 = fig.add_subplot(121)
    ax1.hist(random_data, bucket_count);

with plt.style.context(('tableau-colorblind10')):
    ax2 = fig.add_subplot(122)
    ax2.hist(random_data, bucket_count);
Colorblind matplotlib styles

Here it was easier to see our options side-by-side. You might be familiar with creating subplots, but as a quick reminder, you can add new subplots to a figure by passing in a number which represents [number of rows][number of columns][index]. In practice, this means if we want a single row with two columns, then we pass in 121 for our first plot and 122 for our second!

This is a simple structure that you'll benefit from once you play around with it.

Beyond Python Visual Newsletter

Enjoying the content? We send step-by-step visual Python tutorials to your inbox! Be notified when new content is available by the Beyond Python team.



What do the matplotlib styles look like?

Well, I'm sure you were thinking the same thing when you saw the list of built-in styles.. what do they all look like? Let's see if we can iterate over the styles with what we learned above.

# Calculate what size grid we would need to view
# all the styles at once. This means taking the
# square root of the length of available styles.
import math
style_count = len(plt.style.available)
grid_dimension = math.ceil(math.sqrt(style_count))

fig = plt.figure(figsize=(12, 12))
fig.suptitle('Matplotlib Style Gallery')

for i, style in enumerate(plt.style.available):
    with plt.style.context((style)):
        axis = fig.add_subplot(grid_dimension, grid_dimension, i+1)
        axis.set_title(style, {'fontsize': 8})
        axis.hist(random_data, bucket_count);

# Leave horizontal space for axis titles
plt.subplots_adjust(hspace=0.45)
matplotlib style gallery
Combining matplotlib styles

We are able to see how styles impact different visual attributes of a plot. We are actually able to layer multiple styles, allowing us to establish firm-wide style guidelines and overriding them for specific occasions. You could imagine having a great set of styles for day-to-day use that need to be enlarged for print or presentation.

with plt.style.context(['dark_background', 'seaborn-deep']):
    plt.hist(random_data, bucket_count)
Combining matplotlib styles

This simply shows you how the layering works. The list of styles is processed in order, allowing for the styles later in the list to override the rules established earlier on. This means we see the bar colors from seaborn-deep have overridden any bar colors from dark_background.

Creating your own matplotlib style

If you find that these styles still aren't perfect for you and you are still doing a lot of modifications to get the plots to look the way you want, then you may eventually want to work on developing your own style sheet. Matplotlib allows for a lot of customization. Check out the documentation for details on creating your own style sheet.




Questions, Comments, Concerns?

Thanks for reading! If you've made it this far then you are probably interested in the material that we will be producing. We have an idea of what we believe will be most valuable to our readers, but hearing from you directly would be even better.

Send us an email at questions@beyondpython.com or reach out to us on twitter @BeyondPython

If you have a topic that you are struggling with, a file that you can't seem to work with, or even a dataset that just seems impossible to wrangle, then please let us know. We want to provide you with useful and practical information so you can start using Python today.

Beyond Python Visual Newsletter

Enjoying the content? We send step-by-step visual Python tutorials to your inbox! Be notified when new content is available by the Beyond Python team.



Disclosures & Privacy
All Rights Reserved
© 2019 Beyond Python