Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Change the default background color for Matplotlib plots
Matplotlib allows you to customize the background color of plots using several methods. You can change the face color of individual subplots or set global defaults for all plots.
Default Background Color
Let's first check the default background color ?
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
print("Default face color is:", ax.get_facecolor())
Default face color is: (1.0, 1.0, 1.0, 1.0)
Changing Background Color Using set_facecolor()
The most common method is using set_facecolor() on the axis object ?
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=[10, 4])
# Subplot with default background
plt.subplot(121)
x = np.random.rand(10)
y = np.random.rand(10)
plt.plot(x, y, 'bo-')
plt.title("Default Background Color")
# Subplot with custom background
plt.subplot(122)
ax = plt.gca()
ax.set_facecolor("lightblue")
plt.plot(x, y, 'ro-')
plt.title("Custom Background Color")
plt.tight_layout()
plt.show()
Using Different Color Formats
You can specify colors using various formats ?
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 2, figsize=[8, 6])
x = np.linspace(0, 10, 50)
y = np.sin(x)
# Different color formats
colors = ['lightgreen', '#FFE4B5', (0.9, 0.9, 0.8), 'lavender']
titles = ['Named Color', 'Hex Color', 'RGB Tuple', 'Another Named Color']
for i, (ax, color, title) in enumerate(zip(axes.flat, colors, titles)):
ax.set_facecolor(color)
ax.plot(x, y)
ax.set_title(title)
plt.tight_layout()
plt.show()
Setting Global Background Color
To change the default background color for all future plots ?
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Set global background color
mpl.rcParams['axes.facecolor'] = 'lightgray'
# Create multiple plots with the new default
fig, axes = plt.subplots(1, 2, figsize=[8, 3])
x = np.linspace(0, 5, 20)
axes[0].plot(x, x**2, 'b-')
axes[0].set_title("Plot 1")
axes[1].plot(x, np.exp(x/2), 'r-')
axes[1].set_title("Plot 2")
plt.tight_layout()
plt.show()
# Reset to default
mpl.rcParams['axes.facecolor'] = 'white'
Comparison of Methods
| Method | Scope | When to Use |
|---|---|---|
ax.set_facecolor() |
Single plot/subplot | Individual customization |
rcParams['axes.facecolor'] |
All future plots | Global default setting |
plt.gca().set_facecolor() |
Current active subplot | Quick single plot changes |
Conclusion
Use set_facecolor() for individual plot customization or modify rcParams['axes.facecolor'] to change the global default. Color formats include named colors, hex codes, and RGB tuples.
Advertisements
