是否可以使用 matplotlib 图例选择器选择图例文本区域而不是图例行?
Is it possible to use matplotlib legend picker selecting legend text area not legend line?
我想使用 matplotlib 制作图表。我想添加一个选择器函数,这样我就可以从这个 matplotlib URL 中找到代码:https://matplotlib.org/stable/gallery/event_handling/legend_picking.html
然而,当我执行这段代码时,很难准确地 select 图例线,因为图例线很细。我想修改此代码,以便在单击图例行右侧的图例文本区域时选择器功能起作用。
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()
一个 替代 使用 here 使点击的容忍度 比 legend line
更高,因此更容易点击.
只需将 legline.set_picker(True)
更改为 legline.set_picker(7)
我想使用 matplotlib 制作图表。我想添加一个选择器函数,这样我就可以从这个 matplotlib URL 中找到代码:https://matplotlib.org/stable/gallery/event_handling/legend_picking.html
然而,当我执行这段代码时,很难准确地 select 图例线,因为图例线很细。我想修改此代码,以便在单击图例行右侧的图例文本区域时选择器功能起作用。
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()
一个 替代 使用 here 使点击的容忍度 比 legend line
更高,因此更容易点击.
只需将 legline.set_picker(True)
更改为 legline.set_picker(7)