Make it easier to customize Matplotlib style with your own Python module

Faisal Adam Yudithia
2 min readMar 6, 2022

Did you know that you can change the default Matplotlib style? Yes, as a data enthusiast surely you know how like the example below.

# import module
import matplotlib.pyplot as plt
from matplotlib import rcParams
# set the matplotlib configuration
rcParams['figure.figsize'] = [10.0, 6.0]
rcParams['lines.linestyle'] = '--'
rcParams['lines.linewidth'] = 3
rcParams['xtick.labelsize'] = 'large'
rcParams['ytick.labelsize'] = 'large'

You can run rcParams to find out the keys and values of the Matplotlib configuration in dictionary form. So you can adjust the value by using rcParams[key] = value to set the Matplotlib configuration to your own liking.

But does every project, you have to do that?

You can save your styles as a Python module. So you just need to import the module you created to apply the styles you have set in it.

Before we started, I will show you an example plot with the default configuration.

# import module
import matplotlib.pyplot as plt
# plot with the default configuration
data = [5, 2, 4, 1, 3]
plt.plot(data)
plt.title('Default Configuration')
plt.show()
Output: default configuration

The image above is the output plot generated from the default configuration. So now, let’s start to set the configuration as a Python module!

Step by step:

First, in your JupyterLab/Notebook, create a Python module. I named it mystyle.py (you can name it yourself).

Create python module

Second, open your module you’ve created and code as below.

# import module
from matplotlib import rcParams
# make a dictionary of your own configuration
myparams = {
'figure.figsize' : [10.0, 6.0],
'lines.linestyle' : '--',
'lines.linewidth' : 3,
'xtick.labelsize' : 'large',
'ytick.labelsize' : 'large'
}
# set your own configuration
def set_params():
for key, val in myparams.items():
rcParams[key] = val

You have to import the rcParams from matplotlib libary, then make a dictionary of your own configuration. Finally, set a function to set your own configuration by looping trough the dictionary keys and values.

Last, back to your notebook file and import your module.

# import your module
import mystyle as ms
ms.set_params()
# plot with your own configuration
plt.plot(data)
plt.title('Your Own Configuration')
plt.show()

Now, you just need to call the set_params() function to apply it. It’s easy right?

Visit my GitHub for the details: python-tutorial/mpl-custom-style at main · faisalydth/python-tutorial (github.com)

--

--