Matplotlib创建带有复选按钮图例的图形,用于无限数量的绘图

2024-05-18 21:41:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何使用以下方法为一系列复选按钮的图形创建图例: https://matplotlib.org/3.1.1/gallery/widgets/check_buttons.html

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)

fig, ax = plt.subplots()
l0, = ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz')
l1, = ax.plot(t, s1, lw=2, color='r', label='4 Hz')
l2, = ax.plot(t, s2, lw=2, color='g', label='6 Hz')
plt.subplots_adjust(left=0.2)

lines = [l0, l1, l2]

# Make checkbuttons with all plotted lines with correct visibility
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
labels = [str(line.get_label()) for line in lines]
visibility = [line.get_visible() for line in lines]
check = CheckButtons(rax, labels, visibility)


def func(label):
    index = labels.index(label)
    lines[index].set_visible(not lines[index].get_visible())
    plt.draw()

check.on_clicked(func)

plt.show()

我的特殊问题是,随着我们测试更多的样本,大量的图表将不断增加。如何构造代码,以便在运行或更新代码时,在所附代码中称为行的列表可以不断添加新的plt.subplot条目

谢谢


Tags: importindexplotmatplotlibchecknplinepi
1条回答
网友
1楼 · 发布于 2024-05-18 21:41:34

IIUC,您可以这样做,并创建一个返回行句柄的函数。然后使用append更新列表。随着子批的增长,调用addplotlines自定义函数来创建附加句柄

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)

fig, ax = plt.subplots()

def addplotlines(t,s, color, label, visible=True):
    l, = ax.plot(t, s, visible=visible, lw=2, color=color, label=label)
    plt.subplots_adjust(left=0.2)
    return l

lines = []
lines.append(addplotlines(t, s0, 'k', '2 Hz', False))
lines.append(addplotlines(t, s1, 'r', '4 Hz', True))
lines.append(addplotlines(t, s2, 'g', '6 Hz', True))

# Make checkbuttons with all plotted lines with correct visibility
rax = plt.axes([0.05, 0.4, 0.1, 0.15])
labels = [str(line.get_label()) for line in lines]
visibility = [line.get_visible() for line in lines]
check = CheckButtons(rax, labels, visibility)


def func(label):
    index = labels.index(label)
    lines[index].set_visible(not lines[index].get_visible())
    plt.draw()

check.on_clicked(func)

plt.show()

相关问题 更多 >

    热门问题