10.7 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonHow to Change Background Color in Matplotlib (With Examples)

How to Change Background Color in Matplotlib (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories