How to Change Background Color in Matplotlib (With Examples)


The easiest way to change the background color of a plot in Matplotlib is to use the set_facecolor() argument.

If you define a figure and axis in Matplotlib using the following syntax:

fig, ax = plt.subplots()

Then you can simply use the following syntax to define the background color of the plot:

ax.set_facecolor('pink')

This tutorial provides several examples of how to use this function in practice.

Example 1: Set Background Color Using Color Name

The following code shows how to set the background color of a Matplotlib plot by using the name of a color:

import matplotlib.pyplot as plt

#define plot figure and axis
fig, ax = plt.subplots()

#define two arrays for plotting
A = [3, 5, 5, 6, 7, 8]
B = [12, 14, 17, 20, 22, 27]

#create scatterplot and specify background color to be pink
ax.scatter(A, B)
ax.set_facecolor('pink')

#display scatterplot
plt.show()

Background color in Matplotlib

Example 2: Set Background Color Using Hex Color Code

The following code shows how to set the background color of a Matplotlib plot by using a hex color code:

import matplotlib.pyplot as plt

#define plot figure and axis
fig, ax = plt.subplots()

#define two arrays for plotting
A = [3, 5, 5, 6, 7, 8]
B = [12, 14, 17, 20, 22, 27]

#create scatterplot and specify background color to be pink
ax.scatter(A, B)
ax.set_facecolor('#33FFA2')

#display scatterplot
plt.show()

Matlplotlib background color using hex color code

Example 3: Set Background Color of Specific Subplot

Sometimes you’ll have more than one Matplotlib plot. In this case, you can use the following code to specify the background color for a single plot:

import matplotlib.pyplot as plt

#define subplots
fig, ax = plt.subplots(2, 2)
fig.tight_layout()

#define background color to use for each subplot
ax[0,0].set_facecolor('blue')
ax[0,1].set_facecolor('pink')
ax[1,0].set_facecolor('green')
ax[1,1].set_facecolor('red')

#display subplots
plt.show()

Matplotlib subplots with different backgrounds

Related: How to Adjust Spacing Between Matplotlib Subplots

Leave a Reply

Your email address will not be published.