How to Set Plot Background Color in Matplotlib

Jinku Hu Feb 02, 2024
  1. Set Background Color of the Specific Matplotlib Plot
  2. Set Default Plot Background Color for Multiple Plots in Matplotlib
How to Set Plot Background Color in Matplotlib

set_facecolor(color) of the axes object sets the background color, or in other words, face color of the corresponding Matplotlib plot.

Matplotlib Set Plot Background Color

Set Background Color of the Specific Matplotlib Plot

We need to get the axes object before calling the set_facecolor() method.

1. Matlab-Alike Stateful API in Matplotlib

plt.plot(x, y)
ax = plt.gca()

Complete Example Codes:

import matplotlib.pyplot as plt

plt.plot(range(5), range(5, 10))

ax = plt.gca()
ax.set_facecolor("m")
plt.show()

2. Create Figure and Axis in Object-Oriented Method

figure and axes objects could be created together,

fig, ax = plt.subplots()

Or create a figure first, and then initiate the axes afterward.

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

Complete Example Codes:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(1)

ax.plot(range(5), range(5, 10))

ax.set_facecolor("m")
plt.show()

Or,

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.plot(range(5), range(5, 10))

ax.set_facecolor("m")
plt.show()

Set Default Plot Background Color for Multiple Plots in Matplotlib

If we need to set the default background color for multiple plots, we could set the axes.facecolor property in the rcParams object.

plt.rcParams["axes.facecolor"] = color

Complete Example Codes:

import matplotlib.pyplot as plt

plt.rcParams["axes.facecolor"] = "m"

plt.subplot(1, 2, 1)
plt.plot(range(5), range(5, 10))

plt.subplot(1, 2, 2)
plt.plot(range(5), range(10, 5, -1))

plt.show()

Matplotlib Set Plot Background Color_rcParams

As you see, the background color of the two plots is the same.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - Matplotlib Color