How to change background color in Matplotlib with Python

In this article, we will learn how to change background color in Matplotlib with Python. we need some basic concepts of two python module named as:-

  1. Matplotlib
  2. Numpy

Actually, we are going to change the background color of any graph or figure in matplotlib with python. We have to first understand how this work, as there is a method to change the background color of any figure or graph named as “set_facecolor“.

Changing the background color of the graph in Matplotlib with Python

Let’s understand with some examples:-

  • In 1st  example, we simply draw the graph with the default background color(White).
  • And in 2nd example, we draw the graph and change the background color to Grey.
  • Finally, in 3rd example, we draw the graph and change the background color to Orange.

Example:- 01

import matplotlib.pyplot as plt
import numpy as np
# Creating numpy array
X = np.array([1,2,3,4,5])
Y = X**2

# Setting the figure size
plt.figure(figsize=(10,6))

plt.plot(X,Y)
plt.show()

Output:-

before changing background color in matplotlib

In the above example, the background color of the graph is default(White), so first, we need to import two python module “matplotlib” and “numpy” by writing these two lines:-

  1. import matplotlib.pyplot as plt
  2. import numpy as np

Now, we created the numpy array and stored this in a variable named X and established the relation between X and Y. Then, we set the size of figure with method “plt.figure(figsize=(10,6))” where width=10 and height=6 and then we plotted the graph by “plt.plot(X,Y)“.

Example:- 02

import matplotlib.pyplot as plt
import numpy as np

# Creating the numpy array
X = np.array([1,2,3,4,5])
Y = X**2

# Setting the figure size
plt.figure(figsize=(10,6))
ax = plt.axes()

# Setting the background color
ax.set_facecolor("grey")

plt.plot(X,Y)
plt.show()

Output:-

change background color in Matplotlib with Python

In this example we are doing the same thing as in the above example, the only thing we did different from the above example is using “ax.set_facecolor(“grey”)” to change the background color of graph or figure.

Example:- 03

import matplotlib.pyplot as plt
import numpy as np

# Creating the numpy array
X = np.array([1,2,3,4,5])
Y = X**2

# Setting the figure size
plt.figure(figsize=(10,6))
ax = plt.axes()

# Setting the background color
ax.set_facecolor("orange")

plt.plot(X,Y)
plt.show()

Output:-

matplotlib background color yellow

In this example, we only changed the background color to Orange, and the rest explanation is the same as explained above.

You may also read these articles:-

How to set axis range in Matplotlib Python

Set or Change the Size of a Figure in Matplotlib with Python

Leave a Reply

Your email address will not be published. Required fields are marked *