Reputation:
This may seem like a duplicate, but I swear I tried to find a compatible answer.
I have a set of histograms of different properties of the same 3 samples. So I want a legend with the name of these tree samples.
I tried defining the same labels('h1','h2' and 'h3') in all histograms, like this:
plt.subplot(121)
plt.hist(variable1[sample1], histtype = 'step', normed = 'yes', label = 'h1')
plt.hist(variable1[sample2], histtype = 'step', normed = 'yes', label = 'h2')
plt.hist(variable1[sample3], histtype = 'step', normed = 'yes', label = 'h3')
plt.subplot(122)
plt.hist(variable2[sample1], histtype = 'step', normed = 'yes', label = 'h1')
plt.hist(variable2[sample2], histtype = 'step', normed = 'yes', label = 'h2')
plt.hist(variable2[sample3], histtype = 'step', normed = 'yes', label = 'h3')
Then I used:
plt.legend( ['h1', 'h2', 'h3'], ['Name Of Sample 1', 'Name Of Sample 2', 'Name Of Sample 3'],'upper center')
The legend appears, but is empty. Any ideas?
Upvotes: 1
Views: 361
Reputation: 87356
You have two problems. The first is that you are misunderstanding what label
does. It does not mark the artists to be accessed via that name, but provides the text used by legend
if you call legend
with out any arguments. The second problem is that bar
does not have an auto-generated legend handler.
fig, (ax1, ax2) = plt.subplots(1, 2)
h1 = ax1.hist(variable1[sample1], histtype='step', normed='yes', label='h1')
h2 = ax1.hist(variable1[sample2], histtype='step', normed='yes', label='h2')
h3 = ax1.hist(variable1[sample3], histtype='step', normed='yes', label='h3')
ha = ax2.hist(variable2[sample1], histtype='step', normed='yes', label='h1')
hb = ax2.hist(variable2[sample2], histtype='step', normed='yes', label='h2')
hc = ax2.hist(variable2[sample3], histtype='step', normed='yes', label='h3')
# this gets the line colors from the first set of histograms and makes proxy artists
proxy_lines = [matplotlib.lines.Line2D([], [], color=p[0].get_edgecolor()) for (_, _, p) in [h1, h2, h3]]
fig.legend(proxy_lines, ['label 1', 'label 2', 'label 3'])
also see http://matplotlib.org/users/legend_guide.html#using-proxy-artist
Upvotes: 1