1

I've copied some code from Stackoverflow to use a secondary Y-axis in order to improve the readability of my diagram. Sadly, only the legend to one y-axis is displayed.

The ones displayed are the ones that I include using plt.legend(). However, if I try to display both, using

ax1.legend()

ax2.legend()

Only the latter are shown. Here is the complete code

import matplotlib.pyplot as plt

x,y1,y2,y3,y4=[1,2],[0.5,1],[1,4],[1,2],[1,1.5]

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

ax1.plot(x, y1, 'g-', label='y1')
ax1.plot(x, y2, 'r-', label='y2')
ax2.plot(x, y3, 'b-', label='y3')
ax2.plot(x, y4, 'y-', label='y4')

ax1.legend()

ax2.legend()

plt.show()

enter image description here How can all be shown in the legend?

cheesus
  • 1,111
  • 1
  • 16
  • 44
  • 1
    probably the legend of ax2 is overlapping the legend of ax1, can can check the postion of the legends? https://stackoverflow.com/questions/44413020/how-to-specify-legend-position-in-matplotlib-in-graph-coordinates/44414858 – PV8 Aug 08 '19 at 05:48

1 Answers1

1

You could try to use:

plt.legend(loc='upper left')

instead of of:

ax1.legend()

ax2.legend()

Probably in your original data your labels are overlapping and only the last one (ax2) is displayed.

PV8
  • 5,799
  • 7
  • 43
  • 87
  • 1
    Spot on! - They were overlapping. ax1.legend(loc="upper left") ax2.legend(loc="upper right") displayed them correctly. – cheesus Aug 08 '19 at 06:04