0

My code for graphing is as below:

ax30 = df5.plot(kind="scatter", x='Data Numbers', y='y', color="red", label="67890")
ax33 = ax30.twinx()
df8.plot(kind="scatter", x='Data Numbers', y='y', color="blue", label="12345", ax=ax33, secondary_y = True)

ax30.set_ylabel("A")
ax33.set_ylabel("B")
ax30.set_xlabel("C")
ax30.set_title("DDD")
ax30.set_xlim([0,150])
ax30.set_ylim([0,40000])
ax33.set_xlim([0,150])
ax33.set_ylim([0,40000])

I am trying to plot a data with two different y axis, but it seems like the legends are overlapping. How can I overcome this issue and put the legends back together?The current figure is as below:

Current resulting figure from the code

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • You defined your problem differently but I think this question will provide you with answers: https://stackoverflow.com/questions/5484922/secondary-axis-with-twinx-how-to-add-to-legend – Martyna Nov 04 '18 at 20:20

1 Answers1

0

This solution should stack the labels vertically, removing any overlap:

ax30 = df5.plot(kind="scatter", x='Data Numbers', y='y', color="red", label="67890")
ax33 = df8.plot(kind="scatter", x='Data Numbers', y='y', color="blue", label="12345", ax=ax33, secondary_y = True)

plt.legend([ax30 , ax33], ['label_1', 'label_2'], loc=1)
Sam Comber
  • 1,237
  • 1
  • 15
  • 35