How can I change the background color in Matplotlib? Please provide some examples.

Changing the background color in Matplotlib can be done by using the “figure” object and the “set_facecolor()” method. This method allows the user to specify the desired color for the background. For example, to change the background color to black, the code would be: “plt.figure().set_facecolor(‘black’)”. Other colors can also be used, such as ‘white’, ‘blue’, or RGB values. Additionally, the “rcParams” function can be used to set the default background color for all plots in a script. Overall, changing the background color in Matplotlib is a simple process that can be customized to suit the user’s preferences.

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.pyplotas 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.pyplotas 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.pyplotas 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

x