Chapter 34. Customizing Matplotlib: Configurations and Stylesheets

While many of the topics covered in previous chapters involve adjusting the style of plot elements one by one, Matplotlib also offers mechanisms to adjust the overall style of a chart all at once. In this chapter we’ll walk through some of Matplotlib’s runtime configuration (rc) options, and take a look at the stylesheets feature, which contains some nice sets of default configurations.

Plot Customization by Hand

Throughout this part of the book, you’ve seen how it is possible to tweak individual plot settings to end up with something that looks a little nicer than the default. It’s also possible to do these customizations for each individual plot. For example, here is a fairly drab default histogram, shown in Figure 34-1.

In [1]: import matplotlib.pyplot as plt
        plt.style.use('classic')
        import numpy as np

        %matplotlib inline
In [2]: x = np.random.randn(1000)
        plt.hist(x);
pdsh2 3401
Figure 34-1. A histogram in Matplotlib’s default style

We can adjust this by hand to make it a much more visually pleasing plot, as you can see in Figure 34-2.

In [3]: # use a gray background
        fig = plt.figure(facecolor='white')
        ax = plt.axes(facecolor='#E6E6E6')
        ax.set_axisbelow(True)

        # draw solid white gridlines
        plt.grid(color='w', linestyle='solid')

        # hide axis spines
        for spine in ax.spines.values():
            spine.set_visible(False)

        # hide top and right ...

Get Python Data Science Handbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.