31

I have the following example code:

fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
legend([ax1,ax2], loc=2)

The subplot has two axes with different scales on the same subplot and I want only one legend for both axes. I tried the above code and it does not work and only produces details from ax2. Any ideas?

arun
  • 1,350
  • 1
  • 9
  • 10
  • See http://stackoverflow.com/questions/5484922/secondary-axis-with-twinx-how-to-add-to-legend for the same question. And is gives also the same solution. – joris Jan 16 '13 at 08:26
  • 2
    Yes, it does. My search on SO did not bring it up. Also, the question does not state it needs a single legend on title. But thanks for letting me know. I was wondering if there was something more elegant that what I came up with. Maybe we should add a ax1.combine_legends(ax2) method which does this? – arun Jan 17 '13 at 15:17

2 Answers2

86

I figured it a solution that works! Is there a better way than this?

fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc=2)
arun
  • 1,350
  • 1
  • 9
  • 10
  • This is the only solution that worked for me when having a scatter plot and a regular plot on one figure. Good one! – MattSt Oct 31 '18 at 12:47
  • What if you aren't using "labels" for the plotting because there are multiple lines from a pandas df? – Leland Feb 07 '23 at 01:05
11

This is indeed an old post, but I think I found an easier way allowing more control.

Here it is (matplotlib.version'1.5.3') on python3.5:

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
plt.suptitle('Test')
ax2 = ax1.twinx()
a, =  ax1.plot([1, 2, 3], [4, 5, 6], color= 'blue', label= 'plt1')
b, = ax2.plot([7, 8, 9],[10, 11, 12], color= 'green', label= 'plt2')
p = [a, b]
ax1.legend(p, [p_.get_label() for p_ in p],
           loc= 'upper center', fontsize= 'small')

show()

zx485
  • 28,498
  • 28
  • 50
  • 59
Cy Bu
  • 1,401
  • 2
  • 22
  • 33