Matplotlib 图例

1 投票
1 回答
837 浏览
提问于 2025-04-18 09:10

我在使用这个例子来让图例可以被点击:

    # -*- coding: utf-8 -*-

import os
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 0.2, 0.1)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Click on legend line to toggle line on/off')
line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ')
line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ')
leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)


# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
    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()

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

plt.show()

我想知道的是:如何修改这个程序,让它在一开始只显示一个包含图例的窗口(通过点击图例来显示图表)

像这样:

像这样

这样做可以吗?

1 个回答

1

是的,在第一次出现的 plt.show() 之前,添加这四行代码:

line1.set_visible(False)
line2.set_visible(False)
leg.get_lines()[0].set_alpha(0.2)
leg.get_lines()[1].set_alpha(0.2)

撰写回答