Unable to create draggable legend when using twinx

When I create a plot with two y-axes (left and right) using ax.twinx(), draggable legends don’t work.The legend is only draggable for the 2nd y axis (right), but not for the original y axis (left).

matplotlib v3.2.0

%matplotlib widget
import matplotlib.pyplot as plt
import numpy as np 

x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)

fig, ax = plt.subplots()
ax_twin = ax.twinx()
ax.set_xlabel('X axis')
ax.set_ylabel('Left Y axis (Red)')
ax_twin.set_ylabel('Right Y axis (Blue)')

ax.plot(x, y, label='Left', color='r') 
ax_twin.plot(x, y**-0.5, label='Right', color='b')
 
ax_legend = ax.legend()
ax_legend.set_draggable(True)

ax_twin_legend = ax_twin.legend()
ax_twin_legend.set_draggable(True)

plt.show()

c&p @anntzer.lee

that’s likely because the events don’t get propagated to the second (original) axes – only the topmost axes receive mouse/keyboard events …
yet another thing that should probably be fixed at some point

edit: also @01baftb thank you for your patience with us!

1 Like

The issue is that when the mouse event come into the figure they start propagating down the z-stack of Artists in the Figure until one of them handles it and the event propagation stops. In many cases this is what you want, but not in this case.

See https://github.com/matplotlib/matplotlib/issues/10009 for more details. In principle this propagation behaviour can be fixed / extended but it is a non-trivial amount of work to get right.

1 Like

@tacaswell @story645 Thank you for the response and all the hard work your team is doing on development of matplotlib. I was just helping report a possible bug. :slight_smile:

1 Like