Good day. The minimal code provided below allows the user to click on a legend element to hide/show the associated data set. For some reason, it only works on one of the ax
es despite the code being highly "regular" and not treating the last ax in a different way. The first ax does not seem to pick pick_event
s. How to fix that?
Click the bubbles to test:
import numpy as np
import matplotlib.pyplot as plt
# Create dummy data.
fig = plt.gcf()
ax1 = plt.gca()
ax2 = ax1.twinx()
X = np.arange(-5, +5.01, 0.5)
Y1 = -X**2
Y2 = -0.5*X**2
ax1.scatter(X, Y1, color="red", label="1")
ax2.scatter(X, Y2, color="blue", label="2")
ax1.legend(loc="upper left")
ax2.legend(loc="upper right")
ax1.set_ybound(+5, -30)
ax2.set_ybound(+5, -30)
# Enable the pickable legend elements.
for ax in (ax1, ax2):
for legend_item in ax.get_legend().legendHandles:
legend_item.set_gid("1" if ax is ax1 else "2")
legend_item.set_picker(10)
# Connect the pick event to a function.
def hide_or_show_data(event):
"""Upon clicking on a legend element, hide/show the associated data."""
artist = event.artist
gid = artist.get_gid()
if gid == "1":
scatter = ax1.collections[0]
elif gid == "2":
scatter = ax2.collections[0]
scatter.set_visible(not scatter.get_visible())
plt.draw()
fig.canvas.mpl_connect("pick_event", hide_or_show_data)
My gut feeling is that ax1
ignores events because it's "below" ax2
if that makes any sense.