Single legend for multiple axes [duplicate]

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)

Leave a Comment