How to change axes background color in Matplotlib?

To change the axes background color in Matplotlib, we can use the set_facecolor() method. This method allows us to customize the background color of the plotting area to make our visualizations more appealing or to match specific design requirements.

Using set_facecolor() Method

The most straightforward approach is to get the current axes and apply set_facecolor() ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Get current axes and set background color
ax = plt.gca()
ax.set_facecolor("orange")

# Create data points
x = np.linspace(-2, 2, 10)
y = np.exp(-x)

# Plot the data
plt.plot(x, y, color='red', linewidth=2)
plt.title("Exponential Decay with Orange Background")

plt.show()

Using subplot() with facecolor

You can also set the background color when creating subplots ?

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot with background color
fig, ax = plt.subplots(figsize=(8, 4), facecolor='lightgray')
ax.set_facecolor('lightblue')

# Create sample data
x = np.linspace(0, 10, 50)
y = np.sin(x)

# Plot the data
ax.plot(x, y, color='darkblue', linewidth=2)
ax.set_title("Sine Wave with Light Blue Background")
ax.grid(True, alpha=0.3)

plt.show()

Multiple Background Colors

For multiple subplots, you can set different background colors for each ?

import numpy as np
import matplotlib.pyplot as plt

# Create data
x = np.linspace(0, 2*np.pi, 100)

# Create subplots with different background colors
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

# First subplot - green background
ax1.set_facecolor('lightgreen')
ax1.plot(x, np.sin(x), 'blue', linewidth=2)
ax1.set_title('Sine Wave')

# Second subplot - pink background  
ax2.set_facecolor('lightpink')
ax2.plot(x, np.cos(x), 'red', linewidth=2)
ax2.set_title('Cosine Wave')

plt.tight_layout()
plt.show()

Common Background Colors

Color Name Hex Code Use Case
lightgray #D3D3D3 Neutral, professional
lightblue #ADD8E6 Calm, scientific
wheat #F5DEB3 Warm, presentations
lavender #E6E6FA Soft, elegant

Conclusion

Use set_facecolor() to customize axes background colors in Matplotlib. You can apply it to individual axes or multiple subplots to create visually appealing and professional-looking plots that match your design requirements.

Updated on: 2026-03-25T21:56:17+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements