How to change the face color of a plot using Matplotlib?

Matplotlib allows you to customize the background color of your plots using the set_facecolor() method. This is useful for creating visually appealing plots or matching specific design requirements.

Basic Face Color Change

The simplest way to change the face color is using the set_facecolor() method on the axes object ?

import matplotlib.pyplot as plt
import numpy as np

# Create data points
x = np.linspace(-10, 10, 100)
y = np.sin(x)

# Create figure and axes
fig, ax = plt.subplots(figsize=(8, 4))

# Plot the data
ax.plot(x, y, color='yellow', linewidth=3)

# Set the face color
ax.set_facecolor('lightblue')

plt.title('Plot with Light Blue Background')
plt.show()

Using Different Color Formats

You can specify colors using various formats including color names, hex codes, or RGB tuples ?

import matplotlib.pyplot as plt
import numpy as np

# Create sample data
x = np.linspace(0, 10, 50)
y1 = np.exp(-x/5) * np.cos(x)
y2 = np.exp(-x/5) * np.sin(x)

# Create subplots with different face colors
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

# Plot 1: Using color name
axes[0].plot(x, y1, 'b-', linewidth=2)
axes[0].set_facecolor('lightyellow')
axes[0].set_title('Color Name')

# Plot 2: Using hex code
axes[1].plot(x, y2, 'r-', linewidth=2)
axes[1].set_facecolor('#f0f0f0')
axes[1].set_title('Hex Code')

# Plot 3: Using RGB tuple
axes[2].plot(x, y1 + y2, 'g-', linewidth=2)
axes[2].set_facecolor((0.9, 0.9, 1.0))
axes[2].set_title('RGB Tuple')

plt.tight_layout()
plt.show()

Setting Face Color at Figure Level

You can also set the face color for the entire figure using fig.patch.set_facecolor() ?

import matplotlib.pyplot as plt
import numpy as np

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

# Create figure
fig, ax = plt.subplots(figsize=(8, 4))

# Set figure face color (background around the plot)
fig.patch.set_facecolor('lightgray')

# Set axes face color (plot area background)
ax.set_facecolor('white')

# Plot the data
ax.plot(x, y, 'blue', linewidth=2)
ax.grid(True, alpha=0.3)

plt.title('Figure vs Axes Face Color')
plt.show()

Comparison of Methods

Method Affects Usage
ax.set_facecolor() Plot area only Most common approach
fig.patch.set_facecolor() Entire figure Background around plot
plt.gca().set_facecolor() Current axes When using pyplot interface

Conclusion

Use ax.set_facecolor() to change the background color of the plot area. You can specify colors using names, hex codes, or RGB tuples to match your design requirements.

Updated on: 2026-03-26T02:59:32+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements