Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(14, 8))
y = np.random.randint(0, 100, size=50)
x = np.random.choice(np.arange(len(y)), size=10)
line, = ax.plot(y, '-', label='line')
dot, = ax.plot(x, y[x], 'o', label='dot')
legend = plt.legend(loc='upper right')
line_legend, dot_legend = legend.get_lines()
line_legend.set_picker(True)
line_legend.set_pickradius(10)
dot_legend.set_picker(True)
dot_legend.set_pickradius(10)
graphs = {}
graphs[line_legend] = line
graphs[dot_legend] = dot
def on_pick(event):
legend = event.artist
isVisible = legend.get_visible()
graphs[legend].set_visible(not isVisible)
legend.set_visible(not isVisible)
fig.canvas.draw()
plt.connect('pick_event', on_pick)
plt.show()

Hi,
this code was very informative, as I am just learning how to incorporate widgets in Python. I struggled for hours trying to make the marker for the scatter plot vanish when the dots were toggled off, as the line is made to vanish in the legend for the line graph, but I couldn’t do it. If you add a marker to your first line, you will see that when you toggle the line visibility to False, the line and its markers do disappear from the graph, but only the line disappears from the legend, the marker is still visible in the legend.
Can you edit your code above to include the option to hide also the markers from the legend when you toggle the lines to be visible=False?
Thanks,
Higrm