Set Plot Background Color in Matplotlib

  1. Set Background Color of the Specific Matplotlib Plot
  2. Set Default Plot Background Color for Multiple Plots 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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Matplotlib Color

  • Set Color for Scatterplot in Matplotlib
  • Related Article - Matplotlib rcParams

  • Set Color for Scatterplot in Matplotlib