Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label is Missing from matplotlib legend

Tags:

matplotlib

I'm plotting subplots with matplotlib and the legend does not show up for some plots. In this example, the scatter plot legend does not show up.

import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
from matplotlib.patches import Rectangle, Circle

fig = plt.figure()
plt.cla()
plt.clf()

x = np.arange(5) + 1
y = np.full(5, 10)
fig, subplots = plt.subplots(2, sharex=False, sharey=False)
subplots[0].bar(x, y, color='r', alpha=0.5, label='a')
scat = subplots[0].scatter(x, y-1, color='g', label='c')
subplots[0].set_yscale('log')

subplots[1].bar(x, y, color='r', alpha=0.5, label='a')
x = [2, 3]
y = [4, 4]
subplots[1].bar(x, y, color='b', alpha=1, label='b')
subplots[1].set_yscale('log')

plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), handler_map={scat: HandlerLine2D(numpoints=4)})

plt.show()

Here is what I tried as a workaround:

p1 = Rectangle((0, 0), 1, 1, fc="r", alpha=0.5)
p2 = Rectangle((0, 0), 1, 1, fc="b")
p3 = Circle((0, 0), 1, fc="g")
legend([p1, p2, p3], ['a', 'b', 'c'], loc='center left', bbox_to_anchor=(1, 0.5))

I really prefer to fix this without the workaround so if anyone knows how to fix it please let me know. Also, an issue with the workaround is that the Circle object still appears as a bar on the legend.

like image 463
max Avatar asked Oct 19 '25 14:10

max


1 Answers

plt.legend starts with a gca() (which returns the current axes):

# from pyplot.py:
def legend(*args, **kwargs):
   ret = gca().legend(*args, **kwargs)

So calling plt.legend will only get you a legend on your last subplot. But it is also possible to call e.g. ax.legend(), or in your case subplots[0].legend(). Adding that to the end of your code gives me a legend for both subplots.

Sample:

for subplot in subplots:
    subplot.legend(loc='center left', bbox_to_anchor=(1, 0.5))
like image 68
Bart Avatar answered Oct 23 '25 14:10

Bart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!