2

I want to make a graph using matplotlib. I would like to add a picker function so I can find a code from this matplotlib URL: https://matplotlib.org/stable/gallery/event_handling/legend_picking.html

However when I execute this code, it is very hard to exactly select legend line because of thin legend line. I want to modify this code so that the picker function works when legend text area, right to the legend line, is clicked.

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 1)
y1 = 2 * np.sin(2*np.pi*t)
y2 = 4 * np.sin(2*np.pi*2*t)

fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
line1, = ax.plot(t, y1, lw=2, label='1 Hz')
line2, = ax.plot(t, y2, lw=2, label='2 Hz')
leg = ax.legend(fancybox=True, shadow=True)

lines = [line1, line2]
lined = {}  # Will map legend lines to original lines.

for legline, origline in zip(leg.get_lines(), lines):
    print(legline)
    print(origline)
    legline.set_picker(True)  # Enable picking on the legend line.
    lined[legline] = origline

def on_pick(event):
    # On the pick event, find the original line corresponding to the legend
    # proxy line, and toggle its visibility.
    legline = event.artist
    origline = lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
LeeJunYoung
  • 47
  • 1
  • 5
  • 2
    The [Plotly](https://plotly.com/python/line-charts/) graphing library has this legend picking feature automatically enabled for any plot. Plotly is great for interactive plots, but if you need a static one then perhaps this isn't the best solution. – Jacob K Aug 04 '21 at 01:08

1 Answers1

0

One alternative used here makes the tolerance for clicking the legend line higher so it's easier to click.

Simply change from legline.set_picker(True) to legline.set_picker(7)

thenarfer
  • 405
  • 2
  • 14