How To Create And Use Custom Matplotlib Style Sheet | by Shan Dou | Towards Data Science

The aesthetics of data visualizations are important. I often view this as “beautiful data deserves beautiful presentations” — Being overly fastidious with graph styling is not encouraged, but a healthy amount of polishing could go a long way.
Nevertheless, for static graphs that we typically make with matplotlib or seaborn, the default aesthetics usually require tweaking. This is where custom style sheets come in handy for at least two reasons:
Make our workflow compliant with the Don’t Repeat Yourself (DRY) principle: We don’t need to type the same chunks of styling codes repetitively every time. Instead, we apply the style sheet with one line of code
Styling consistency is easily achieved, and that could be an implicit signature for individuals, teams, and organizations
Most of us may already have been using a few built-in styles in day-to-day work. For example, a quick run of
# This code snippet mimics command usages in ipython consoleIn [1]: import matplotlib.pyplot as pltOut [1]: plt.style.available
will return a full list of style sheets, and we can find a gallery view of their effects in matplotlib’s documentation.
Under the hood, we can locate these built-in style sheets and take a look:
# This code snippet mimics command usages in ipython consoleIn [2]: import matplotlib# Locate path to matplotlib by checking where config file is# To learn more about the function below,# type ?matplotlib.matplotlib_fnameIn [3]: matplotlib.matplotlib_fname()Out [3]: '/Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/matplotlibrc'
The path /Users/.../mpl-data is where we would like to go and locate the style sheets:
In [4]: !ls /Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/fonts           images          matplotlibrc    stylelib
The folder of interest is stylelib. Let’s now take a look inside this folder:
In [5]: !ls -1 /Users/sdou/opt/miniconda3/lib/python3.8/site-packages/matplotlib/mpl-data/stylelib/Solarize_Light2.mplstyle_classic_test_patch.mplstylebmh.mplstyleclassic.mplstyledark_background.mplstylefast.mplstylefivethirtyeight.mplstyleggplot.mplstylegrayscale.mplstyleseaborn-bright.mplstyleseaborn-colorblind.mplstyleseaborn-dark-palette.mplstyleseaborn-dark.mplstyleseaborn-darkgrid.mplstyleseaborn-deep.mplstyleseaborn-muted.mplstyleseaborn-notebook.mplstyleseaborn-paper.mplstyleseaborn-pastel.mplstyleseaborn-poster.mplstyleseaborn-talk.mplstyleseaborn-ticks.mplstyleseaborn-white.mplstyleseaborn-whitegrid.mplstyleseaborn.mplstyletableau-colorblind10.mplstyle
Let’s inspect one of the .mplstyle files. Here we use classic.mplstyle as an example and display the top 37 lines of the file:
We can see a comprehensive list of matplotlib parameter settings and their default values, and the parameters are organized into groups such as lines, markers, patch, text.
Below is a minimalism example (named signature.mplstyle)built on top of the built-in style sheetseaborn-colorblind.mplstyle
If we have write privilege to the abovementioned path for stylelib, we can put the custom style sheet into the same folder and invoke the style sheet with
# Scenario 1: Apply globally to a jupyter notebookplt.style.use(“signature”)# Scenario 2: Apply locally with context managerwith plt.style.context("signature"):    plt.plot([1, 2, 3, 4])
If we don’t have the write privilege, the only extra thing we would need to do is to include the full path of the custom style sheet. Here we use a simple example of directly storing the style sheet under the home directory:
# Scenario 1: Apply globally to a jupyter notebookplt.style.use(“/home/signature.mplstyle”)# Scenario 2: Apply locally with context managerwith plt.style.context("/home/signature.mplstyle"):    plt.plot([1, 2, 3, 4])
There could be cases when we want to recover the default styling. There are at two ways to recover the default settings:
Reset via rcParams.update
Reset via rcParams.update
import matplotlib as mplmpl.rcParams.update(mpl.rcParamsDefault)
2. Reset with default style sheet
plt.style.use('default')
Here we penguin dataset as an example to demonstrate the effect of the custom style sheet signaure.mplstyle.
import matplotlib.pyplot as pltimport seaborn as sns# Load the penguins datasetpenguins = sns.load_dataset("penguins")
Use default style
Use default style
plt.style.use("default")# Show the joint distribution using kernel density estimationg = sns.jointplot(    data=penguins,    x="bill_length_mm",    y="bill_depth_mm",    hue="species",    kind="kde",)g.fig.suptitle("Styled With Default Style Sheet", y=1.01)plt.show()
2. Use custom style set in signature.mplstyle
plt.style.use("signature")# Show the joint distribution using kernel density estimationg = sns.jointplot(    data=penguins,    x="bill_length_mm",    y="bill_depth_mm",    hue="species",    kind="kde",)g.fig.suptitle("Styled With Custom Style Sheet", y=1.01)plt.show()
Beautiful data deserves beautiful presentations. But instead of typing chunks of styling codes repetitively, a bit upfront time investment in setting up our own custom style sheet (file extension .mplstyle) could both save time and ensure styling consistency
To build custom style sheets, we could start with built-in style sheets and custom them further to our liking. One key step is to locate these style sheets with the help of matplotlib.matplotlib_fname()
4.11 Customizing Matplotlib: Configurations and Stylesheets: Data Science Handbook by Jake VanderPlas