Skip to content
Related Articles

Related Articles

Change Legend background using facecolor in MatplotLib
  • Last Updated : 22 Jan, 2021

In this article, we will see how can we can change the background color of a legend in our graph using MatplotLib, Here we will take two different examples to showcase different background colors of a legend in our graph.

Requirements:

pip install matplotlib

Approach:

  • Import required module.
  • Create data.
  • Change the background color of a legend.
  • Normally plot the data.
  • Display plot.

Implementation:

Example 1:



In this example, we will draw different lines with the help of matplotlib and Use the facecolor argument to plt.legend() to specify the legend background color.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing package 
import matplotlib.pyplot as plt 
import numpy as np 
  
# create data 
X = [1,2,3,4,5
Y = [3,3,3,3,3
  
# plot lines 
plt.plot(X, Y, label = "Line-1"
plt.plot(Y, X, label = "Line-2"
plt.plot(X, np.sin(X), label = "Curve-1"
plt.plot(X, np.cos(X), label = "Curve-2"
  
#Change the background color of a  legend.
plt.legend(facecolor="gray")
plt.title("Line Graph - Geeksforgeeks")
  
plt.show()

chevron_right


Output:

Example 2:

In this example, we will draw a Vertical line with the help of matplotlib and Use the facecolor argument to plt.legend() to specify the legend background color.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing package 
import matplotlib.pyplot as plt 
  
#Create data and plot lines.
plt.plot([0, 1], [0, 2.0], label='Label-1')
plt.plot([1, 2], [0, 2.1], label='Label-2')
plt.plot([2, 3], [0, 2.2], label='Label-3')
  
#Change the background color of a  legend.
plt.legend(facecolor="pink")
plt.title("Line Graph - Geeksforgeeks")
  
plt.show()

chevron_right


Output:


Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :