How to change plot background color in Matplotlib?

Matplotlib provides two methods of changing the background color of a plot:

  1. Using axes.set_facecolor(color) method to set the background color of the plot.
  2. Set the default background color of the plot by assigning a color to the plt.rcParams['axes.facecolor'].

How to change plot background color using axes.set_facecolor(color) method?

axes.set_facecolor(color) method changes the background color of the plot on which you have called this function and does not affect the other axes.

Let's understand how to change the background color of the plot with some examples:

The first example assumes that you are not using subplots. Here, you need to get the current axes object, call the set_facecolor() function on that object, and pass the color you want for the plot.

import matplotlib.pyplot as plt

ax = plt.gca()
ax.set_facecolor('red')

x = [1,2,3,4,5,6]
y = [1,2,3,4,5,6]
plt.plot(x,y)
plt.show()

Output

Matplotlib change background color

In the second example, we are using subplots. Here, you have the axes objects. All you have to do is simply call set_facecolor(color) on the axes object, and it will change the background color of that axes only and does not affect the other plots.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(20,8))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

x = [1,2,3,4,5,6]
y = [1,2,3,4,5,6]
ax1.plot(x,y)
ax1.set_facecolor('yellow')
ax1.set_title('Axes 1 Title')
ax1.set_xlabel('Axes 1 X Axis')
ax1.set_ylabel('Axes 1 Y Axis')

x = [1, 1, 3, 2, 2, 3, 4, 5, 4, 7]
y = [4, 3, 2, 4, 7, 4, 1, 10, 3, 2]
ax2.scatter(x,y)
ax2.set_title('Axes 2 Title')
ax2.set_xlabel('Axes 2 X Axis')
ax2.set_ylabel('Axes 2 Y Axis')

plt.show()

Output

Matplotlib plot background color

How to set plot background color using plt.rcParams['axes.facecolor']?

You have to assign a color to the plt.rcParams['axes.facecolor']. Once you assign the color to it, all the subsequent plots that will be plotted by Matplotlib will use the updated background color set by you. In other words, plt.rcParams['axes.facecolor'] changes the default background color of all the plots.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(20,8))
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)
fig.suptitle('Figure Title')
plt.rcParams['axes.facecolor'] = 'yellow'

x = [1,2,3,4,5,6]
y = [1,2,3,4,5,6]
ax1.plot(x,y)
ax1.set_title('Axes 1 Title')
ax1.set_xlabel('Axes 1 X Axis')
ax1.set_ylabel('Axes 1 Y Axis')

x = [1, 1, 3, 2, 2, 3, 4, 5, 4, 7]
y = [4, 3, 2, 4, 7, 4, 1, 10, 3, 2]
markersSize = [162, 66, 161, 34, 60, 217, 132, 205, 207, 120]
ax2.scatter(x, y, s=markersSize)
ax2.set_title('Axes 2 Title')
ax2.set_xlabel('Axes 2 X Axis')
ax2.set_ylabel('Axes 2 Y Axis')

plt.show()

Output

Matplotlib default background color

Note: If you want to revert the background color of the plot to the initial default value then run the below code:
plt.rcParams['axes.facecolor'] = 'white'