0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Change Background Color in Matplotlib Plots

To change the background color in matplotlib, use plt.figure(facecolor='color') to set the figure background or ax.set_facecolor('color') to change the plot area background. Replace 'color' with any valid color name or hex code.
๐Ÿ“

Syntax

There are two main ways to change background colors in Matplotlib:

  • Figure background: Use plt.figure(facecolor='color') to set the color behind the entire plot.
  • Axes background: Use ax.set_facecolor('color') to change the color inside the plot area where data is drawn.

Replace 'color' with a color name like 'lightblue', 'white', or a hex code like '#f0f0f0'.

python
plt.figure(facecolor='color')
ax.set_facecolor('color')
๐Ÿ’ป

Example

This example shows how to set the figure background to light gray and the plot area background to light yellow.

python
import matplotlib.pyplot as plt

fig = plt.figure(facecolor='#d3d3d3')  # light gray background for figure
ax = fig.add_subplot()
ax.set_facecolor('#ffffe0')  # light yellow background for plot area
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Background Color Example')
plt.show()
Output
A plot window with a light gray outer background and a light yellow plot area showing a line graph with points (1,4), (2,5), (3,6). The title reads 'Background Color Example'.
โš ๏ธ

Common Pitfalls

Common mistakes when changing background colors include:

  • Setting the figure background but expecting the plot area to change color (or vice versa).
  • Using invalid color names or formats, which causes errors or no visible change.
  • Not calling plt.show() to display the plot after changes.

Always check if you want to change the whole figure background or just the plot area.

python
import matplotlib.pyplot as plt

# Wrong: setting figure background but expecting plot area color change
fig = plt.figure(facecolor='lightblue')
ax = fig.add_subplot()
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()

# Right: set axes facecolor for plot area
fig = plt.figure()
ax = fig.add_subplot()
ax.set_facecolor('lightblue')
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()
Output
Two plot windows: first with light blue figure background but white plot area, second with white figure background but light blue plot area.
๐Ÿ“Š

Quick Reference

MethodDescriptionExample
plt.figure(facecolor='color')Set background color of entire figureplt.figure(facecolor='lightgray')
ax.set_facecolor('color')Set background color of plot area (axes)ax.set_facecolor('#ffffe0')
plt.gca().set_facecolor('color')Set plot area color using current axesplt.gca().set_facecolor('lightgreen')
โœ…

Key Takeaways

Use plt.figure(facecolor='color') to change the whole figure background color.
Use ax.set_facecolor('color') to change the plot area background color.
Colors can be named strings or hex color codes.
Make sure to call plt.show() to see the changes.
Check if you want to change figure or axes background to avoid confusion.