我用matplotlib来绘制数据。如所附图像中所示,用于显示每一行的复选框与表示线条颜色的图例是分开的。是否有一种将复选框和图例组合在一起的方法,以便复选框、通道名称和对应行的颜色都在一个框架框中相邻?
下面是我的代码:
ch0, = plt.plot(df['Time (s)'], df['Piezo Channel 0 (V)'], label='CH0', linewidth=0.3)
ch1, = plt.plot(df['Time (s)'], df['Piezo Channel 1 (V)'], label='CH1', linewidth=0.3)
ch2, = plt.plot(df['Time (s)'], df['Piezo Channel 2 (V)'], label='CH2', linewidth=0.3)
ch3, = plt.plot(df['Time (s)'], df['Piezo Channel 3 (V)'], label='CH3', linewidth=0.3)
ch4, = plt.plot(df['Time (s)'], df['Piezo Channel 4 (V)'], label='CH4', linewidth=0.3)
ch5, = plt.plot(df['Time (s)'], df['Piezo Channel 5 (V)'], label='CH5', linewidth=0.3)
channel = [ch0, ch1, ch2, ch3, ch4, ch5]
plt.legend(loc='upper right', frameon=False)
plt.title('Piezosensor Output (Channel 0-5)', loc='center', pad=16 )
plt.xlabel('Time (s)')
plt.ylabel('Amplitude (V)')
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.95, top=0.95)
label = ['CH0','CH1','CH2','CH3','CH4','CH5']
label_on = [True, True, True, True, True, True]
button_space = plt.axes([0.92, 0.4, 0.15, 0.15])
button = CheckButtons(button_space, label, label_on)
def set_visible(labels):
i = label.index(labels)
channel[i].set_visible(not channel[i].get_visible())
plt.draw()
button.on_clicked(set_visible)
plt.show()发布于 2021-06-18 17:54:11
如果我能很好地理解你的问题,你想去掉这个图例,而把图例的颜色放在CheckButtons矩形中,
您可以通过删除图例并将set_facecolor添加到代码中来实现这一点,最后的代码如下所示:
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import pandas as pd
import numpy as np
ch0, = plt.plot(x, y,'r', label='CH0', linewidth=0.7,visible=True)
ch1, = plt.plot(x, y, label='CH1', linewidth=0.7,visible=True)
ch2, = plt.plot(x, y, label='CH2', linewidth=0.7,visible=True)
ch3, = plt.plot(x, y, label='CH3', linewidth=0.7,visible=True)
ch4, = plt.plot(x, y, label='CH4', linewidth=0.7,visible=True)
ch5, = plt.plot(x, y, label='CH5', linewidth=0.7,visible=True)
channel = [ch0, ch1, ch2, ch3, ch4, ch5]
# plt.legend(loc='upper right', frameon=False)
plt.title('Piezosensor Output (Channel 0-5)', loc='center', pad=16 )
plt.xlabel('Time (s)')
plt.ylabel('Amplitude (V)')
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.95, top=0.95)
label = ['CH0','CH1','CH2','CH3','CH4','CH5']
label_on = [True, True, True, True, True, True]
button_space = plt.axes([0.92, 0.4, 0.15, 0.15])
button = CheckButtons(button_space, label, label_on)
def set_visible(labels):
i = label.index(labels)
channel[i].set_visible(not channel[i].get_visible())
plt.draw()
[rec.set_facecolor(channel[i].get_color()) for i, rec in enumerate(button.rectangles)]
button.on_clicked(set_visible)
plt.show() 在[rec.set_facecolor(channel[i].get_color()) for i, rec in enumerate(button.rectangles)]中,我使用get_color()获取线条的当前颜色,而set_facecolor()则将该颜色设置为矩形的正面。
https://stackoverflow.com/questions/68038538
复制相似问题