1

我想创建一个带有两个 y 轴和交互式图例的图。我根据以下内容制作了一个最小的“工作”示例:https ://matplotlib.org/3.1.1/gallery/event_handling/legend_picking.html

import matplotlib.pyplot as plt
import numpy as np


t = np.arange(0.0, 5, 0.01)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)+1

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')
ax2 = ax.twinx()
line2, = ax2.plot(t, y2, lw=2, label='2 HZ')
lines_twinx=[line1,line2]
lbl = [l.get_label() for l in lines_twinx]
leg=ax.legend(lines_twinx, lbl, loc="upper left",fontsize='xx-small', shadow=True)
leg.get_frame().set_alpha(0.4)
lined = dict()

for legline, origline in zip(leg.get_lines(), lines_twinx):
    legline.set_picker(5)  # 5 pts tolerance
    lined[legline] = origline


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

    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

情节图

不知何故,图例不可点击。有人知道该怎么做吗?

4

1 回答 1

1

使用fig.legend()而不是ax.legend()帮助我

leg=fig.legend(lines_twinx, lbl, loc="upper left",fontsize='xx-small', shadow=True)

在这里查看

于 2020-06-21T17:02:00.173 回答