A Guide to Creating and Using Your Own Matplotlib Style | by Naveen Venkatesan | Towards Data Science

Although the default appearance of plots made using matplotlib can appear somewhat drab, I really enjoy the customizability that allows you to tweak every single tiny element of your plot.
If you find yourself consistently changing some of the basic settings in matplotlib every time you create a new figure, it may be fruitful to generate a style file. By importing this style, you can ensure consistency, while still maintaining the ability to override settings as you wish within the individual scripts. This is great if you are, for example, generating figures for a publication and want them all to look the same without having to copy/paste settings each time.
You can find a template for a style file at the matplotlib Github respository. As you see, there are an almost endless number of settings that you can customize as you wish! We will use this as a guide to create our own style file.
Before we begin, we should create an empty plot using the default matplotlib parameters as a basis for comparison:
# Import packagesimport matplotlib.pyplot as plt# Create figurefig = plt.figure()# Add subplot to figureax = fig.add_subplot(111)# Show empty plotplt.show()
First, we must create a file called your_style.mplstyle which we can then edit with the text editor of your choice. I am going to build upon the scientific theme of my first article, so we will create a style called scientific.mplstyle. To run this style, we must place it in our matplotlib configuration directory. An easy way to check for where this is to run the following code:
import matplotlib as mplmpl.get_configdir()
My configuration directory, which is likely similar for most is found as a subfolder of my home directory: ~/.matplotlib/
We place our .mplstyle file in a subdirectory called stylelib. If this folder doesn’t yet exist for you, can create it and put your scientific.mplstyle file into this folder. Now, when you want to use your style, use the following line in your Python script:
plt.style.use('scientific')
First, we can set the figure size, which is normally 6.4 x 4.8 inches. We will use a 4 x 4 inch figure as our default. Now, every time we call plt.figure(), our figure will have dimensions of 4 x 4:
# Figure Propertiesfigure.figsize: 4, 4
Now we can set our font and the default font size. I will use the font ‘Avenir’ and a font size of 16.
# Font Propertiesfont.family: Avenirfont.size: 16
Now that we have changed the global figure properties, let’s edit properties of the axes/subplot objects. First, we want to change the thickness of the axes, which we do using axes.linewidth:
# Axes propertiesaxes.linewidth: 2
Next, I often find that the default padding (whitespace) between the tick labels and the axis labels are too small. We can insert our own custom value of padding with the following:
axes.labelpad: 10
Finally, we will change the default colors that are used when plotting, which can done by editing the color cycler. We do this by creating a cycler() object and passing it to the property axes.prop_cycle. I quite like the colors used in plots on FiveThirtyEight, so will use this as our color cycler. I will be inserting the colors using their HEX codes:
axes.prop_cycle: cycler(color=['008fd5',                                'fc4f30',                                'e5ae38',                               '6d904f',                               '8b8b8b',                               '810f7c'])
Let’s inspect our progress so far! We use the following code:
# Import packagesimport matplotlib.pyplot as plt# Use our custom styleplt.style.use('scientific')# Create figurefig = plt.figure()# Add subplot to figureax = fig.add_subplot(111)# Show empty plotplt.show()
Already looking much better! We notice that the tick marks do not match some of the axes changes we have made, so this will be our next step.
We notice from the default plot that the tick marks are pointed outwards, and there are no ticks on the top or right axes. For our scientific theme, we want the ticks to all point inwards, and we want ticks on all of the axes, which we can do with the following:
# Tick properties# x-axisxtick.top: Truextick.direction: in# y-axisytick.right: Trueytick.direction: in
Now, we want to change the two properties size and width. The value of width corresponds to the linewidth, so we will set this equal to the value we gave for axes.linewidth (2). The value of size is the length of the ticks — we will set major ticks to have a size of 7 and minor ticks to have a size of 5:
# x-axisxtick.major.size: 7xtick.major.width: 2xtick.minor.size: 5xtick.minor.width: 2# y-axisytick.major.size: 7ytick.major.width: 2ytick.minor.size: 5ytick.minor.width: 2
We now have the following figure — the ticks have now been fixed!
If we want to edit any of the default parameters that are used when we make a call to plt.plot() we can do so by editing the properties for lines. This can be extended to other plotting functions — for example, you can edit properties for scatter to affect the default parameters when creating a scatter plot. In our case, I am only going to the change the default width of the lines to 2, from their default value of 1.5:
# Lines propertieslines.linewidth: 2
The default legend in matplotlib is semi-transparent and has a frame with curved corners called a FancyBox. To see this in action we can run the following code, with all the default parameters:
# Import packagesimport matplotlib.pyplot as pltimport numpy as np# Create figurefig = plt.figure()# Add subplot to figureax = fig.add_subplot(111)# Create some datax = np.linspace(0, 4*np.pi, 200)y1 = np.sin(x)y2 = 1.5*np.sin(x)y3 = 2*np.sin(x)# Plot dataax.plot(x, y1, label='A = 1')ax.plot(x, y2, label='A = 1.5')ax.plot(x, y3, label='A = 2')# Add legendax.legend()# Show plotplt.show()
Let’s make the legend fully opaque and remove the frame altogether:
# Legend propertieslegend.framealpha: 1legend.frameon: False
Now, let’s see how the previous plot looks with our new matplotlib style! We use the following code:
# Import packagesimport matplotlib.pyplot as pltimport numpy as np# Use our custom styleplt.style.use('scientific')# Create figurefig = plt.figure()# Add subplot to figureax = fig.add_subplot(111)# Create some datax = np.linspace(0, 4*np.pi, 200)y1 = np.sin(x)y2 = 1.5*np.sin(x)y3 = 2*np.sin(x)# Plot dataax.plot(x, y1, label='A = 1')ax.plot(x, y2, label='A = 1.5')ax.plot(x, y3, label='A = 2')# Set axis labelsax.set_xlabel('x')ax.set_ylabel('y')# Add legend - loc is a tuple specifying the bottom left cornerax.legend(loc=(1.02, 0.65))# Save plotplt.show()
And cue reaction in 3...2...1...
There are still some minor tweaks that we could make, like adjust the scale of the x and y-ticks, but we have made our life so much easier by making our style settings do most of the work for us!
There are endless possibilities for how you can adjust properties to define a style for your matplotlib plots. The scientific.mplstyle file from this article will be available at this Github repository.
Thank you for reading! I appreciate any feedback, and you can find me on Twitter and connect with me on LinkedIn for more updates and articles.