matplotlib如何将复选框与图例合并到同一个带边框容器中
实现方案
你要的合并复选框、颜色标识、通道名的带框控件可以通过修改CheckButtons控件、添加对应曲线颜色样本、给控件区域加边框实现,修改后的可运行代码如下:
import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons import pandas as pd import numpy as np # 模拟数据部分可替换为你自己的df读取逻辑 df = pd.DataFrame({ 'Time (s)': np.linspace(0, 10, 1000), 'Piezo Channel 0 (V)': np.random.randn(1000).cumsum(), 'Piezo Channel 1 (V)': np.random.randn(1000).cumsum(), 'Piezo Channel 2 (V)': np.random.randn(1000).cumsum(), 'Piezo Channel 3 (V)': np.random.randn(1000).cumsum(), 'Piezo Channel 4 (V)': np.random.randn(1000).cumsum(), 'Piezo Channel 5 (V)': np.random.randn(1000).cumsum(), }) 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] label = ['CH0','CH1','CH2','CH3','CH4','CH5'] label_on = [True]*6 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.82, top=0.95) # 创建CheckButtons容器 button_ax = plt.axes([0.85, 0.4, 0.12, 0.2]) # 给控件区域添加边框 button_ax.spines[['top', 'right', 'bottom', 'left']].set_visible(True) button = CheckButtons(button_ax, label, label_on) # 为每个选项添加对应曲线的颜色标识 for idx, (line, label_text) in enumerate(zip(channel, button.labels)): button_ax.text(0.15, label_text.get_position()[1], '_', color=line.get_color(), fontsize=12, fontweight='bold', transform=button_ax.transAxes) def set_visible(lab): idx = label.index(lab) channel[idx].set_visible(not channel[idx].get_visible()) plt.draw() button.on_clicked(set_visible) plt.show()
关键修改说明
- 删除了原本独立的legend控件,避免重复显示
- 给CheckButtons所在的axes开启了spines边框,生成带框效果
- 遍历所有曲线,在每个复选框的标签前添加了和曲线同色的颜色标识,三者在同一行排列
- 调整了主图的右边界,避免控件遮挡绘图内容
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

