How to set local rcParams or rcParams for one figure in matplotlib?

In matplotlib, you can temporarily change rcParams for a specific figure using the plt.rc_context() context manager. This allows you to apply custom styling to one figure without affecting global settings.

Using rc_context() for Local rcParams

The plt.rc_context() function creates a temporary context where rcParams are modified locally. Once the context exits, the original settings are restored ?

import numpy as np
import matplotlib.pyplot as plt

# Set global figure properties
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True

# Generate sample data
N = 10
x = np.random.rand(N)
y = np.random.rand(N)

# Create figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)

# Left subplot with local rcParams
with plt.rc_context({"axes.grid": True, "grid.linewidth": 2, "lines.linestyle": 'dashed'}):
    ax1.plot(x, y, 'bo-')
    ax1.set_title('With Custom Grid')

# Right subplot uses default settings
ax2.plot(x, y, 'ro-')
ax2.set_title('Default Settings')

plt.show()

Setting Multiple rcParams

You can modify multiple parameters simultaneously by passing a dictionary to rc_context() ?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 50)
y = np.sin(x)

# Custom styling parameters
custom_params = {
    'lines.linewidth': 3,
    'lines.color': 'red',
    'axes.facecolor': 'lightgray',
    'grid.alpha': 0.5,
    'axes.grid': True
}

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))

# Apply custom parameters locally
with plt.rc_context(custom_params):
    ax1.plot(x, y)
    ax1.set_title('Custom Styling')

# Default parameters
ax2.plot(x, y)
ax2.set_title('Default Styling')

plt.tight_layout()
plt.show()

Comparison of Methods

Method Scope Best For
plt.rcParams[key] = value Global Setting defaults for entire script
plt.rc_context() Local (temporary) One-time custom styling
ax.set_*() methods Axes-specific Individual plot customization

Conclusion

Use plt.rc_context() to temporarily modify rcParams for specific figures without affecting global settings. This approach provides clean, isolated styling that automatically reverts when the context exits.

Updated on: 2026-03-26T19:02:45+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements