Hi all, I'm struggling with this: I'd like to put a legend on my plot that is not see through. I tried facecolor white, frameaalpha=1, whichever I do the legend it still see through. I also tried to put a white patch where the legend is and put the legend on top, but I can't make it go over the patch. =/ anyone knows how to make it so that my legend sits in a nice white box on top / covering that part of the figure?
facealpha
or alpha
?
nope, facealpha doesn't exist, alpha is an unexpected keyword
Try plt.legend(facecolor='white', framealpha=1)
, from https://stackoverflow.com/questions/19863368/matplotlib-legend-background-color
pasted image doesn't work for me, the same with plt. doesn't work either
Try this
legend = plt.legend(loc='upper left', frameon=1, framealpha=1) frame = legend.get_frame() frame.set_color('white')
Thanks @Max Grover , that works. I think the key here is that I have two axes, so I have to gather my labels and use plt.legend()
rather than ax.legend()
. pasted image
Awesome- I will add this onto the FAQ page. Thanks for bringing up this question - I am sure plenty of other people have had similar struggles with the nuances of matplotlib!
pasted image doesn't work for me, the same with plt. doesn't work either
ah I see what's happening, the second axis is on top of the first axis (which has the legend), so those colored bars are on top of the legend. if you change the zorder
for the second axis, it should work the easy way. I bet Max's solution is adding the legend on the second axis, so it works. I also bet the get_frame
workaround isn't doing anything.
correct, it works with the commented line as well (though that way it has a frame around the legend that I didn't like). How do I change zorder
ax.set_zorder(-1)
? There's some subtlety here. If the background for the first axis is not transparent, you wouldn't see it. I would just add the legend after doing the fill_*
call (which is what plt.legend
is doing)
Last updated: May 16 2025 at 17:14 UTC