Matplotlib

Matplotlib Tutorial – Chapter 13: Styling and Themes

Chapter 13 – Styling and Themes in Matplotlib

By default, Matplotlib plots look simple and functional. However, with a few styling adjustments, you can transform them into professional-quality visuals that match your project’s theme or publication standards.

This chapter covers how to apply built-in styles, define custom color palettes, and modify global parameters for consistent design.

✅ Why Styling Matters

A well-styled chart enhances readability and communicates insights effectively.
Using themes and style sheets saves time and ensures that all your plots share a consistent visual language.

✅ What You’ll Learn

  • Applying built-in style sheets
  • Creating your own custom styles
  • Using rcParams for fine control
  • Choosing and customizing color palettes
  • Adjusting fonts, grids, and figure backgrounds

✅ 1. Built-in Style Sheets

Matplotlib includes several predefined themes that you can apply easily.


import matplotlib.pyplot as plt

print(plt.style.available)

This prints a list of all available styles such as:


['seaborn', 'ggplot', 'classic', 'bmh', 'dark_background', 'fast', 'Solarize_Light2']

To apply a style globally:


plt.style.use('ggplot')
plt.plot([1, 2, 3], [2, 4, 3])
plt.title("Styled with ggplot")
plt.show()

✅ 2. Temporary Style Contexts

You can use a style temporarily for a specific plot block using a with statement.


import matplotlib.pyplot as plt

with plt.style.context('seaborn-v0_8-darkgrid'):
    plt.plot([1, 2, 3], [4, 2, 5])
    plt.title("Temporary Style Example")
    plt.show()

After the block ends, Matplotlib reverts to the default style automatically.

✅ 3. Customizing rcParams

Matplotlib uses a global dictionary called rcParams to store default settings like font sizes, colors, and figure sizes.

You can view or change them like this:


import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (8, 5)
mpl.rcParams['font.size'] = 12
mpl.rcParams['axes.titlesize'] = 14

Or reset everything:


mpl.rcdefaults()

✅ 4. Adjusting Fonts and Text Styles

You can change the global font family or text color using rcParams:


mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['text.color'] = '#333333'

Example:


plt.title("Sales Growth", fontsize=16, fontweight='bold', color='darkblue')
plt.xlabel("Month", fontsize=12)
plt.ylabel("Revenue", fontsize=12)

✅ 5. Changing Backgrounds and Grids

Background and grid colors significantly affect chart readability.


plt.style.use('seaborn-v0_8-darkgrid')
plt.plot([10, 20, 30], [15, 25, 20])
plt.title("Dark Grid Background")
plt.show()

Or custom style:


ax = plt.gca()
ax.set_facecolor('#f0f0f0')
plt.grid(color='gray', linestyle='--', linewidth=0.5)

✅ 6. Color Palettes and Colormaps

Colors play a key role in visualization aesthetics.
Matplotlib provides various colormaps (from viridis to plasma and coolwarm).


import numpy as np
x = np.linspace(0, 10, 100)
for i, color in enumerate(plt.cm.viridis(np.linspace(0, 1, 5))):
    plt.plot(x, np.sin(x + i), color=color)
plt.title("Using the Viridis Colormap")
plt.show()

You can also use:


plt.colormaps()

to list all available color schemes.

✅ 7. Custom Style Sheet (User-defined)

You can create your own `.mplstyle` file for consistent branding.

Example – my_style.mplstyle:


axes.facecolor : #f7f7f7
axes.edgecolor : #333333
axes.grid      : True
font.size      : 12
font.family    : sans-serif
lines.linewidth: 2

Then apply it globally:


plt.style.use('my_style.mplstyle')

✅ 8. Combining Multiple Styles

You can merge multiple style sheets for complex themes:


plt.style.use(['seaborn-v0_8-darkgrid', 'my_style.mplstyle'])

✅ 9. Previewing All Styles Quickly

You can preview all built-in styles visually:


import matplotlib.pyplot as plt

for style in plt.style.available:
    plt.style.use(style)
    plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
    plt.title(style)
    plt.show()

This helps you choose the one that fits your project best.

✅ 10. Best Practices

  • Use consistent colors for related datasets.
  • Stick to accessible color palettes (e.g., viridis for colorblind safety).
  • Always ensure high contrast between text and background.
  • Define one consistent style sheet for your organization or project.
  • Use minimalistic themes for print or reports, and bold themes for presentations.

✅ Summary

In this chapter, you learned how to make your visualizations beautiful, professional, and consistent by using styles, themes, and rcParams.
You can now easily apply global settings, build your own themes, and use color palettes that enhance data communication.

In the next chapter, we’ll explore 3D Plotting and Surface Visualization — taking your Matplotlib skills into the third dimension!

Leave a Reply

Your email address will not be published. Required fields are marked *