How to Set Plot Background Color in Matplotlib

  1. Set Background Color of the Specific Plot
  2. Set Default Plot Background Color for Multiple Plots in Matplotlib

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

Matplotlib Set Plot Background Color

Set Background Color of the Specific 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 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 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.

Related Article - Matplotlib rcParams