0

How can I make the legend of the original axis the top level? It is currently printed over by the twin axis line. My question is similar to this one, but I am asking about the first legend, not the second. I would also like to keep the grid of the first axis.

fig2,ax2 = subplots()
ax2.cla()
axx2.cla()
axx2 = ax2.twinx()
ax2.plot(1:10, 2:11, label="main", zorder=100)
axx2.plot(1:10, [100 for i in 1:10], label="second", zorder=10, color="black", linewidth=2)
ax2.legend(loc="center left").set_zorder(1002)
ax2.grid(true)
ax2.set_ylabel("main")
axx2.get_yaxis().set_visible(false)

enter image description here


EDIT: solved

fig2, ax1 = plt.subplots()
fig.set_size_inches(18/1.5, 10/1.5)
ax2 = ax1.twinx()
ax1.plot(1:10, 1:10, label="main", linestyle="-")
ax1.grid(true)
ax2.plot(1:10, [100 for i in 1:10], label="second", linestyle="--")
ax1.legend(loc="center left", borderaxespad=1.)
# ax2.legend(loc="upper right", borderaxespad=1.)
legend_1 = ax1.legend(loc="center left", borderaxespad=1.)
legend_1.remove()
# ax2.legend(loc="center left", borderaxespad=1.)
ax2.add_artist(legend_1)
jjjjjj
  • 1,152
  • 1
  • 14
  • 30
  • 1
    Everything on one `ax` is always fully on top or fully beneath the other. You can change the relative z-orders of the `ax`es, via `axx2.set_zorder(-1)` – JohanC Aug 20 '23 at 20:05
  • @JohanC: Thanks for your comment. I've tried something similar before. Unfortunately, if I add `axx2.set_zorder(-1)` to my code, it removes the black line on the twinx. – jjjjjj Aug 20 '23 at 20:10
  • You could try `ax2.set_facecolor('none')` to make that `ax` transparent (instead of the default white). – JohanC Aug 20 '23 at 20:53

0 Answers0