4

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.

0

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Great. Thanks, I added a sample code to your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.