首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有twinx - matplotlib的交互式图例

带有twinx - matplotlib的交互式图例
EN

Stack Overflow用户
提问于 2020-05-20 20:23:22
回答 1查看 201关注 0票数 0

我想创建一个带有两个y轴和交互式图例的图。我做了一个最小的“工作”示例,基于:https://matplotlib.org/3.1.1/gallery/event_handling/legend_picking.html

代码语言:javascript
复制
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()

plot-figure

不知怎么的,图例是无法点击的。有人知道该怎么做吗?

EN

回答 1

Stack Overflow用户

发布于 2020-06-22 01:02:00

fig.legend()代替ax.legend()帮了我大忙

代码语言:javascript
复制
leg=fig.legend(lines_twinx, lbl, loc="upper left",fontsize='xx-small', shadow=True)

view here

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61913062

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档