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

Global Configurations in Matplotlib

Learn how to manage default Matplotlib settings and customize the appearance of charts using global configuration options.

Explore rcParams, matplotlibrc files, configuration values, default settings and configuration reset techniques.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand global configurations in Matplotlib.
  • Explain the purpose of rcParams.
  • Read and update Matplotlib configuration properties.
  • Customize default figure and axes settings.
  • Understand the matplotlibrc configuration file.
  • Reset configuration values to their defaults.
  • Use global settings with multiple charts.
  • Understand the relationship between styles and rcParams.

2. Introduction to Global Configurations

Matplotlib provides global configuration settings that control the default appearance and behaviour of charts.

For example, when creating a chart, Matplotlib uses default values for figure size, font size, line width, colours, grid settings and other visual properties.

Sometimes these default values may not match our project requirements. We can change them using Matplotlib's configuration system.

Example

If we want all subsequently created charts to use a larger default figure size, we can configure it once:

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (10, 5)

This changes the default figure size for figures created afterwards in the current Matplotlib configuration.

3. Understanding rcParams

rcParams is a configuration dictionary provided by Matplotlib. It stores settings that control the default behaviour and appearance of plots.

The name rcParams refers to runtime configuration parameters. We can read and modify these settings directly from Python.

Accessing rcParams

import matplotlib.pyplot as plt

print(plt.rcParams)

Output

RcParams({
    'figure.figsize': [6.4, 4.8],
    'figure.dpi': 100.0,
    'font.size': 10.0,
    'lines.linewidth': 1.5,
    'axes.grid': False,
    ...
})

The output above is an abbreviated illustration. The complete configuration contains many more properties, and their values may depend on your Matplotlib installation and configuration.

Tip: Use plt.rcParams when you want to inspect or modify Matplotlib's current configuration directly from Python.

4. Reading Individual Configuration Values

We can access a particular configuration property by using its key inside plt.rcParams.

Example

import matplotlib.pyplot as plt

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

Output

Figure Size: [6.4, 4.8]
Figure DPI: 100.0
Font Size: 10.0
Line Width: 1.5
Grid Enabled: False

These are common default values in a standard Matplotlib configuration. Actual values may differ if a style or configuration file has changed them.

5. Modifying Global Configuration Settings

We can modify a configuration value by assigning a new value to its corresponding rcParams key.

Syntax

plt.rcParams['property_name'] = new_value

Example

import matplotlib.pyplot as plt

# Change default configuration
plt.rcParams['figure.figsize'] = (10, 5)
plt.rcParams['font.size'] = 14
plt.rcParams['lines.linewidth'] = 2.5
plt.rcParams['axes.grid'] = True

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: 14.0
Line Width: 2.5
Grid Enabled: True

The modified configuration values are used by subsequently created figures and plotting elements, unless they are overridden by another setting.

6. Important Matplotlib Configuration Properties

Matplotlib supports many rcParams properties. The following table lists commonly used properties for chart customization.

Property Purpose Example Value
figure.figsize Default figure width and height in inches. (10, 5)
figure.dpi Default figure resolution. 100
savefig.dpi Default resolution for saved figures. 150
figure.facecolor Default figure background colour. white
axes.facecolor Default plotting area background. #f8fafc
axes.grid Enables or disables axes grid lines. True
axes.titlesize Default axes title font size. 16
axes.labelsize Default axes label font size. 12
font.size Default font size. 12
lines.linewidth Default line width. 2
lines.markersize Default marker size. 7
legend.fontsize Default legend font size. 10

7. Configuring Figure Properties

Figure properties control the overall figure, including its size, resolution and background colour.

Example

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (10, 5)
plt.rcParams['figure.dpi'] = 120
plt.rcParams['figure.facecolor'] = 'white'

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

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

plt.title('Figure Configuration Example')
plt.xlabel('X Values')
plt.ylabel('Y Values')

plt.show()

Output

Figure displayed with:
- Figure width: 10 inches.
- Figure height: 5 inches.
- Figure DPI: 120.
- White figure background.
- Line chart with five data points.

These settings define the default figure configuration for figures created after the settings are applied.

8. Configuring Axes Properties

Axes configuration controls the appearance of the plotting area, including its background, grid lines, title and labels.

Example

import matplotlib.pyplot as plt

plt.rcParams['axes.facecolor'] = '#f8fafc'
plt.rcParams['axes.edgecolor'] = '#334155'
plt.rcParams['axes.grid'] = True
plt.rcParams['axes.titlesize'] = 16
plt.rcParams['axes.labelsize'] = 12

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

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

plt.title('Axes Configuration')
plt.xlabel('X Values')
plt.ylabel('Y Values')

plt.show()

Output

Chart displayed with:
- Light plotting area background.
- Customized axes border colour.
- Grid lines enabled.
- Customized title font size.
- Customized axes label font size.

9. Configuring Font Properties

Font configuration controls the default text appearance across Matplotlib charts.

We can configure font family, font size and other font-related settings using rcParams.

Example

import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.size'] = 13
plt.rcParams['axes.titleweight'] = 'bold'

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

plt.plot(x, y)

plt.title('Font Configuration')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')

plt.show()

Output

Chart displayed with:
- Sans-serif font family.
- Default font size of 13.
- Bold axes title.
- Customized text appearance.
Tip: Font availability depends on the operating system and installed fonts. Matplotlib may use a fallback font if the requested font is unavailable.

10. Configuring Line and Marker Properties

We can also define default line width, line style, marker size and marker edge width through global configuration settings.

Example

import matplotlib.pyplot as plt

plt.rcParams['lines.linewidth'] = 3
plt.rcParams['lines.linestyle'] = '--'
plt.rcParams['lines.markersize'] = 9
plt.rcParams['lines.markeredgewidth'] = 1.5

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

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

plt.title('Line and Marker Configuration')
plt.show()

Output

Chart displayed with:
- Default line width of 3.
- Dashed line style.
- Marker size of 9.
- Marker edge width of 1.5.

These properties provide a common default appearance for lines created after the configuration is applied.

11. Understanding the matplotlibrc File

Matplotlib also supports a configuration file called matplotlibrc. This file allows users to define default settings outside the Python program.

Instead of writing configuration commands in every Python script, we can store settings in a configuration file.

Example matplotlibrc Configuration

# Matplotlib Configuration File

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

figure.facecolor: white
axes.facecolor: #f8fafc

axes.grid: True
grid.color: #cccccc

font.size: 12
axes.titlesize: 16

lines.linewidth: 2.5
lines.markersize: 7

When Matplotlib loads this configuration file, the defined settings become part of its default configuration.

How It Works

Matplotlib searches for its configuration file using its configuration directory and configuration search rules. The file location can depend on the environment and setup.

We can inspect the active configuration file location using matplotlib.matplotlib_fname().

import matplotlib

print(matplotlib.matplotlib_fname())

Output

C:\Users\Username\.matplotlib\matplotlibrc

This is an illustrative Windows path. Your actual output will show the configuration file location used by your Matplotlib installation.

12. Finding the Matplotlib Configuration Directory

Matplotlib provides a function to identify the configuration directory used by the current Python environment.

Example

import matplotlib

print(matplotlib.get_configdir())

Output

C:\Users\Username\.matplotlib

The returned directory is an example. The actual directory depends on the operating system, user account and environment.

The configuration directory is useful when managing Matplotlib configuration files and related settings.

13. Resetting Configuration Settings

Sometimes we modify many configuration properties and want to restore the original default settings.

Matplotlib provides plt.rcdefaults() to reset rcParams to the default values.

Example

import matplotlib.pyplot as plt

# Modify configuration
plt.rcParams['font.size'] = 18
plt.rcParams['lines.linewidth'] = 4
plt.rcParams['axes.grid'] = True

print("Before Reset:")
print("Font Size:", plt.rcParams['font.size'])
print("Line Width:", plt.rcParams['lines.linewidth'])

# Reset configuration
plt.rcdefaults()

print("\nAfter Reset:")
print("Font Size:", plt.rcParams['font.size'])
print("Line Width:", plt.rcParams['lines.linewidth'])

Output

Before Reset:
Font Size: 18.0
Line Width: 4.0

After Reset:
Font Size: 10.0
Line Width: 1.5

The output illustrates the common default values after resetting the configuration. Your environment may have different defaults.

Important: plt.rcdefaults() restores Matplotlib's default configuration values. It does not delete or modify your matplotlibrc file on disk.

14. Temporary Configuration with rc_context()

Sometimes we need to change configuration settings only for a particular section of code.

Matplotlib provides plt.rc_context() to apply temporary rcParams changes. The previous configuration is restored after the context ends.

Example

import matplotlib.pyplot as plt

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

with plt.rc_context({
    'font.size': 16,
    'lines.linewidth': 3,
    'axes.grid': True
}):
    plt.plot(x, y, marker='o')
    plt.title('Temporary Configuration')
    plt.show()

# Previous configuration is restored here
plt.plot(x, y)
plt.title('Original Configuration')
plt.show()

Output

First chart:
- Font size is temporarily set to 16.
- Line width is temporarily set to 3.
- Grid lines are enabled.

Second chart:
- Uses the configuration that was active
  before entering rc_context().
Tip: Use plt.rc_context() when you need temporary configuration changes without permanently modifying the active rcParams settings.

15. Difference Between rcParams and Style Sheets

Both rcParams and style sheets help customize Matplotlib charts. However, they provide different ways to manage configuration settings.

Feature rcParams Style Sheets
Purpose Directly access and modify configuration values. Store reusable groups of configuration settings.
Format Python configuration object. Text-based .mplstyle file or built-in style.
Modification Change individual settings using Python. Apply multiple settings through a style.
Temporary Changes Use rc_context(). Use style.context().
Best Use Programmatic configuration changes. Reusable visual themes.

Style sheets also work through Matplotlib's configuration system. When a style is applied, its properties update the active rcParams configuration.

16. Understanding the Global Configuration Workflow

The following diagram explains the general workflow for configuring Matplotlib before creating a chart.

Import Matplotlib Load Configuration Configure rcParams Create Figure and Plot Display Customized Chart

General workflow for applying global configuration settings before plotting.

17. Practical Example: Configure a Sales Dashboard

In this example, we will configure Matplotlib globally and create two charts using the same default settings.

Python Code

import matplotlib.pyplot as plt

# Global configuration
plt.rcParams['figure.figsize'] = (8, 4)
plt.rcParams['figure.dpi'] = 100
plt.rcParams['font.size'] = 12
plt.rcParams['lines.linewidth'] = 2.5
plt.rcParams['axes.grid'] = True

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']

sales = [100, 130, 125, 170, 200]
profit = [20, 25, 23, 35, 45]

# Sales chart
plt.figure()
plt.plot(months, sales, marker='o')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.show()

# Profit chart
plt.figure()
plt.plot(months, profit, marker='s')
plt.title('Monthly Profit')
plt.xlabel('Month')
plt.ylabel('Profit')
plt.show()

Output

Chart 1:
Monthly Sales
- Figure size: 8 x 4 inches.
- Font size: 12.
- Line width: 2.5.
- Grid enabled.

Chart 2:
Monthly Profit
- Uses the same global configuration.
- Displays profit values for five months.

Both charts use the same global configuration. This helps maintain a consistent appearance across the dashboard.

18. Best Practices for Global Configurations

  • Configure common settings at the beginning of your plotting program.
  • Use meaningful rcParams properties.
  • Check existing values before modifying important settings.
  • Use rc_context() for temporary configuration changes.
  • Use style sheets when you need reusable visual themes.
  • Use matplotlibrc for persistent default configuration.
  • Reset settings when a clean default configuration is required.
  • Avoid unnecessary global changes in large applications.
  • Test charts after modifying configuration values.

19. Common Mistakes and Solutions

Problem Possible Reason Solution
Invalid rcParams key Incorrect property name. Check the correct configuration key.
Invalid configuration value Value does not match the expected type or range. Provide a valid value.
Changes not visible Figure or axes created before configuration changes. Set configuration before creating the figure.
Unexpected chart appearance A style or explicit plotting argument overrides a setting. Check the active style and plotting arguments.
Configuration file not used File is outside the active configuration search location. Check the configuration path and Matplotlib settings.

20. Practice Questions

Basic Questions

  1. What are global configurations in Matplotlib?
  2. What is rcParams?
  3. How can you read a configuration value?
  4. What is the purpose of the matplotlibrc file?
  5. Which function resets Matplotlib settings to defaults?
  6. What is the difference between rcParams and style sheets?

Practical Questions

  1. Change the default figure size to 10 by 5 inches.
  2. Set the default font size to 14.
  3. Enable grid lines using rcParams.
  4. Configure default line width and marker size.
  5. Display the current Matplotlib configuration file path.
  6. Reset modified configuration values using rcdefaults().
  7. Use rc_context() to apply temporary chart settings.
  8. Create two charts using the same global configuration.

Summary

Global configurations in Matplotlib control the default appearance and behaviour of charts. The rcParams configuration system stores settings for figure size, resolution, fonts, colours, axes, grid lines, lines and other plotting elements.

We can access and modify configuration values using plt.rcParams. This allows us to define common chart settings once and reuse them in subsequently created figures.

The matplotlibrc file provides a way to store default configuration settings outside Python programs. Functions such as matplotlib.matplotlib_fname() and matplotlib.get_configdir() help identify the configuration file and directory.

The plt.rcdefaults() function restores default configuration values, while plt.rc_context() provides temporary configuration changes. Together, these features help developers manage chart appearance consistently across Matplotlib projects.