Stream: python-questions
Topic: not see through legend
Anna-Lena Deppenmeier (May 10 2021 at 23:34):
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?
Deepak Cherian (May 10 2021 at 23:36):
facealpha
or alpha
?
Anna-Lena Deppenmeier (May 11 2021 at 01:45):
nope, facealpha doesn't exist, alpha is an unexpected keyword
Brian Bonnlander (May 11 2021 at 05:11):
Try plt.legend(facecolor='white', framealpha=1)
, from https://stackoverflow.com/questions/19863368/matplotlib-legend-background-color
Anna-Lena Deppenmeier (May 11 2021 at 14:05):
pasted image doesn't work for me, the same with plt. doesn't work either
Max Grover (May 11 2021 at 14:14):
Try this
legend = plt.legend(loc='upper left', frameon=1, framealpha=1) frame = legend.get_frame() frame.set_color('white')
Anna-Lena Deppenmeier (May 11 2021 at 14:34):
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
Max Grover (May 11 2021 at 14:36):
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!
Deepak Cherian (May 11 2021 at 16:13):
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.
Anna-Lena Deppenmeier (May 11 2021 at 16:14):
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
Deepak Cherian (May 11 2021 at 16:16):
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: Jan 30 2022 at 12:01 UTC