Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the legend edgecolor and facecolor in matplotlib

Is there while rcParams['legend.frameon'] = 'False' a simple way to fill the legend area background with a given colour. More specifically I would like the grid not to be seen on the legend area because it disturbs the text reading.

The keyword framealpha sounds like what I need but it doesn't change anything.

import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['legend.frameon'] = 'False' plt.plot(range(5), label = u"line") plt.grid(True) plt.legend(loc = best) plt.show() 

I've also tried:

legend = plt.legend(frameon = 1) frame = legend.get_frame() frame.set_color('white') 

but then I need to ask how can I change the background colour while keeping the frame on? Sometimes I want it ON with a background colour other than white. And also, is there a way of changing the colour of the frame? With the above code I was expecting to change the colour of the frame only, not the background.

like image 277
user1850133 Avatar asked Nov 08 '13 16:11

user1850133


People also ask

How do you change the legend in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do I change the legend box size in Matplotlib?

To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.

How do I change the legend color in Matplotlib?

To place the legend, use legend() method with location of the legend and store the returned value to set the color of the text. To set the color of the text, use set_color() method with green color.


2 Answers

You can set the edge color and the face color separately like this:

frame.set_facecolor('green') frame.set_edgecolor('red') 

There's more information under FancyBboxPatch here.

like image 199
Molly Avatar answered Oct 11 '22 01:10

Molly


Using matplotlib.pyplot, plt.legend(facecolor='white', framealpha=1) will give your legend a white background without transparency.

like image 28
oveoyas Avatar answered Oct 11 '22 00:10

oveoyas