Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Custom Style Sheets in Matplotlib

Learn how to create your own Matplotlib style sheets and customize the appearance of charts using reusable configuration files.

Explore the .mplstyle file format, define chart properties, apply custom styles and reuse the same design across multiple plots.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand custom style sheets in Matplotlib.
  • Explain the purpose of an .mplstyle file.
  • Create a custom style sheet.
  • Configure colours, fonts, grid lines and figure properties.
  • Apply a custom style using plt.style.use().
  • Load a style sheet using its file path.
  • Reuse custom styles across multiple Python programs.
  • Understand how to troubleshoot style configuration issues.

2. Introduction to Custom Style Sheets

Matplotlib provides built-in styles, but sometimes the predefined styles do not match the design requirements of a project.

For example, a company may require all charts to use the same background colour, font size, line width and grid appearance. Instead of configuring these properties repeatedly, we can create a custom style sheet.

A Matplotlib custom style sheet is a text file with the .mplstyle extension. It contains configuration settings that control the appearance of plots.

Example

We can create a file named my_style.mplstyle and define chart properties inside it.

figure.figsize: 10, 5
figure.facecolor: white
axes.facecolor: #f8fafc
axes.grid: True
grid.color: #cccccc
lines.linewidth: 2
font.size: 12

Once this file is created, we can apply its settings to Matplotlib plots using a single command.

3. Why Do We Use Custom Style Sheets?

Custom style sheets are useful when we want complete control over chart appearance and need to reuse the same design in different programs.

Benefit Description
Reusable Design Use the same visual configuration in multiple Python files.
Consistent Charts Maintain a common design across project visualizations.
Easy Maintenance Update the style file instead of editing formatting code in every chart.
Brand Customization Use colours and fonts that match an organization's design.
Less Python Code Keep visual configuration separate from plotting logic.

4. Understanding the .mplstyle File

An .mplstyle file is a plain text configuration file. Each line generally contains a Matplotlib configuration parameter followed by its value.

Basic Syntax

property_name: value

Example Style Sheet

# Custom Matplotlib Style

figure.figsize: 10, 5
figure.dpi: 100

figure.facecolor: white
axes.facecolor: #f8fafc

axes.edgecolor: #334155
axes.labelcolor: #1e293b
axes.titleweight: bold

axes.grid: True
grid.color: #cbd5e1
grid.linestyle: --

lines.linewidth: 2
lines.markersize: 7

font.family: sans-serif
font.size: 12

xtick.color: #334155
ytick.color: #334155

legend.frameon: True

In this file, each configuration setting controls a particular part of the chart, such as figure size, background, axes, grid, line appearance or font.

Tip: Lines beginning with # are comments. They help explain the configuration and are not treated as style settings.

5. Important Style Sheet Properties

Matplotlib uses configuration parameters to control different chart elements. The following are commonly used properties in custom style sheets.

Property Purpose Example Value
figure.figsize Sets the default figure width and height in inches. 10, 5
figure.dpi Sets the default figure resolution. 100
figure.facecolor Sets the figure background colour. white
axes.facecolor Sets the plotting area background. #f8fafc
axes.grid Enables or disables grid lines. True
grid.color Sets the grid line colour. #cccccc
lines.linewidth Sets the default line width. 2
lines.markersize Sets the default marker size. 7
font.size Sets the default font size. 12
legend.frameon Controls the legend frame. True

6. Creating Your First Custom Style Sheet

Let's create a custom style sheet that we can use for our sales charts.

Step 1: Create a Project Folder

Create a folder for your Matplotlib project and add a file named custom_sales.mplstyle.

MatplotlibProject/
│
├── main.py
│
└── styles/
    └── custom_sales.mplstyle

Step 2: Add Configuration Properties

Open custom_sales.mplstyle and add the following configuration:

# Custom Sales Chart Style

figure.figsize: 10, 5
figure.dpi: 100
figure.facecolor: white

axes.facecolor: #f8fafc
axes.edgecolor: #334155
axes.labelcolor: #334155
axes.titleweight: bold

axes.grid: True
axes.axisbelow: True

grid.color: #cbd5e1
grid.linestyle: --

lines.linewidth: 2.5
lines.markersize: 7

font.family: sans-serif
font.size: 12

legend.frameon: True

Step 3: Save the File

Save the file using the exact name custom_sales.mplstyle inside the styles folder.

MatplotlibProject 📁 MatplotlibProject 📄 main.py 📁 styles 📄 custom_sales.mplstyle

Example folder structure showing where the custom style sheet is stored.

7. Applying a Custom Style Sheet

After creating the style file, we can load it into our Python program using plt.style.use().

Python Code

import matplotlib.pyplot as plt

# Load custom style sheet
plt.style.use('styles/custom_sales.mplstyle')

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [120, 150, 135, 180, 210]

plt.plot(
    months,
    sales,
    marker='o',
    label='Monthly Sales'
)

plt.title('Monthly Sales Report')
plt.xlabel('Month')
plt.ylabel('Sales')

plt.legend()
plt.show()

Output

Chart displayed with the custom_sales style:

- Figure size: 10 x 5 inches.
- White figure background.
- Light plotting area background.
- Grid lines enabled.
- Custom line width and marker size.
- Custom font and axes colours.
- Legend displayed with a frame.

Matplotlib reads the style configuration from the file and applies those settings to the chart.

Important: The style file path must be correct relative to the current working directory. If the file cannot be found, Matplotlib will raise an error.

8. Loading a Style Sheet Using an Absolute Path

We can also load a custom style sheet by providing its full file path instead of a relative path.

Example

import matplotlib.pyplot as plt

style_path = r"C:\MatplotlibProject\styles\custom_sales.mplstyle"

plt.style.use(style_path)

plt.plot([1, 2, 3, 4], [10, 20, 15, 30])
plt.title('Custom Style Using File Path')

plt.show()

Output

Matplotlib loads the custom style from the
specified absolute file path.

The chart is displayed using the properties
defined inside custom_sales.mplstyle.

The raw string prefix r is useful for Windows paths because it prevents backslashes from being interpreted as escape sequences.

9. Using Multiple Custom Style Sheets

Matplotlib also allows us to apply multiple style sheets together. This can be useful when we want to combine a built-in style with additional custom settings.

Example

import matplotlib.pyplot as plt

plt.style.use([
    'ggplot',
    'styles/custom_sales.mplstyle'
])

x = [1, 2, 3, 4, 5]
y = [15, 25, 20, 35, 45]

plt.plot(x, y, marker='o')

plt.title('Combined Style Example')
plt.xlabel('X Values')
plt.ylabel('Y Values')

plt.show()

Output

Chart displayed using combined style settings.

- ggplot provides the initial style settings.
- custom_sales.mplstyle is applied afterwards.
- Custom settings can override matching properties
  from the earlier style.
Tip: When multiple styles define the same property, later styles in the list take precedence over earlier ones.

10. Using Custom Style Sheets Temporarily

We can use plt.style.context() to apply a custom style temporarily. This is helpful when only a particular chart needs a special design.

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

with plt.style.context('styles/custom_sales.mplstyle'):

    plt.plot(x, y, marker='o')

    plt.title('Temporary Custom Style')
    plt.xlabel('X Values')
    plt.ylabel('Y Values')

    plt.show()

# This chart uses the style active outside the context
plt.plot(x, y)
plt.title('Outside Custom Style')
plt.show()

Output

First chart:
Uses properties from custom_sales.mplstyle.

Second chart:
Uses the style that was active before
entering the temporary style context.

11. Understanding Style Configuration and rcParams

Matplotlib uses a configuration system called rcParams. It stores settings that control the default appearance and behaviour of plots.

Custom style sheets provide a convenient way to define many of these settings in a separate file.

Example

import matplotlib.pyplot as plt

plt.style.use('styles/custom_sales.mplstyle')

print("Figure Size:", plt.rcParams['figure.figsize'])
print("Font Size:", plt.rcParams['font.size'])
print("Line Width:", plt.rcParams['lines.linewidth'])
print("Grid Enabled:", plt.rcParams['axes.grid'])

Output

Figure Size: [10.0, 5.0]
Font Size: 12.0
Line Width: 2.5
Grid Enabled: True

The output shows the configuration values loaded from the custom style sheet, assuming those properties have not been overridden by another configuration.

12. Common Errors and Solutions

Error or Problem Possible Reason Solution
FileNotFoundError Incorrect style file path. Check the file name and path.
Style Not Applied Style loaded after creating the chart. Load the style before creating the figure and axes.
Invalid Parameter Incorrect Matplotlib property name. Check the valid rcParams key.
Invalid Value Unsupported value for a configuration property. Use a valid value for that property.
Unexpected Appearance Another style or explicit plotting argument overrides a setting. Check the style order and plotting arguments.
Important: A custom style sheet only controls properties defined in it. Other properties continue to use the active Matplotlib configuration.

13. Best Practices for Custom Style Sheets

  • Use meaningful names for custom style files.
  • Keep all project style files inside a dedicated folder.
  • Add comments to explain important configuration settings.
  • Use valid Matplotlib rcParams property names.
  • Choose colours that provide sufficient contrast.
  • Keep font sizes readable in reports and presentations.
  • Reuse the same style file across related project charts.
  • Test the style file before using it in production reports.
  • Keep plotting logic separate from visual configuration.

14. Practical Activity: Create a Company Chart Theme

Imagine that a company wants every sales chart to follow the same visual design. Your task is to create a reusable custom style sheet for its monthly sales reports.

Activity Requirements

  1. Create a folder named company_styles.
  2. Create a file named company_theme.mplstyle.
  3. Set the figure size to 10 by 5 inches.
  4. Set a white figure background.
  5. Set a light plotting area background.
  6. Enable grid lines.
  7. Set the default line width to 2.5.
  8. Set the font size to 12.
  9. Apply the style to a monthly sales chart.

Sample Style File

# Company Theme

figure.figsize: 10, 5
figure.facecolor: white

axes.facecolor: #f8fafc
axes.grid: True
axes.axisbelow: True

grid.color: #cbd5e1

lines.linewidth: 2.5
lines.markersize: 7

font.size: 12
axes.titleweight: bold

Python Program

import matplotlib.pyplot as plt

plt.style.use('company_styles/company_theme.mplstyle')

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [100, 130, 125, 170, 190, 230]

plt.plot(months, sales, marker='o', label='Sales')

plt.title('Company Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')

plt.legend()
plt.show()

Output

Company Monthly Sales chart displayed.

The chart uses:
- Company custom theme.
- White figure background.
- Light plotting area.
- Visible grid lines.
- Custom line width and markers.
- Consistent font configuration.

15. Practice Questions

Basic Questions

  1. What is a custom style sheet in Matplotlib?
  2. What is the extension of a Matplotlib style file?
  3. What is the basic syntax inside an .mplstyle file?
  4. Which function applies a custom style sheet?
  5. What is the purpose of rcParams?

Practical Questions

  1. Create a custom style sheet with a white background.
  2. Configure grid lines and line width in an .mplstyle file.
  3. Apply your custom style to a line chart.
  4. Load a style sheet using an absolute file path.
  5. Combine a built-in style with a custom style sheet.
  6. Apply a custom style temporarily using style.context().

Summary

Custom style sheets allow developers to create reusable chart designs in Matplotlib. A style sheet is a plain text file with the .mplstyle extension that contains configuration properties for controlling the appearance of charts.

Properties such as figure size, background colour, axes colour, grid settings, font size, line width and marker size can be configured inside a custom style file.

The plt.style.use() function loads and applies a custom style sheet. We can provide a relative path or an absolute path to the style file. Multiple style sheets can also be combined, with later styles taking precedence for properties they define.

The plt.style.context() function is useful when we want to apply a custom style temporarily. Custom style sheets help maintain consistent visual designs and keep plotting code clean and reusable.