Sunday, 10 September 2023

How to customize legend background color in a plot?

Using ‘facecolor’ parameter of plot.lengend() method, we can customize the legend background color.

 

Example

plt.legend(facecolor='lightgreen')

 

legend_background_color.py

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10)
y1 = x**2
y2 = x**3

plt.plot(x, y1, label="y = x^2", color='r')
plt.plot(x, y2, label="y = x^3", color='g')

plt.legend(facecolor='lightgreen')
plt.show()

Output



In this example, I created a line plot with a legend using plt.legend(facecolor='lightgreen') to set the background color of the legend box to light green.

 

You can use any valid color specification to set the background color, such as named colors, hexadecimal codes, RGB tuples, or RGBA tuples.

 

RGB example

plt.legend(facecolor=(0, 1, 1))

 

RGBA example

plt.legend(facecolor=(1, 0, 0, 0.5))

 

Hexadecimal example

plt.legend(facecolor='#0000FF')

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment