python绘制多曲线图的时候,图像往往很杂,不利于观察分析部分曲线的趋势。
请教各位,如何在绘制的图像出现后,在图像上添加每条曲线显示或隐藏的开关,观察图像时选中几条曲线显示,其他曲线隐藏,便于观察~
多次采用
sub.plot(x,y)
曲线1:y = 10 * x
曲线2:y2 = 8 * x
曲线3:y3 = 10 - 5 * x
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
x = np.linspace(0, 1, 100)
y = 10 * x
y2 = 8 * x
y3 = 10 - 5 * x
fig = plt.figure()
sub = fig.add_subplot(111)
sub.plot(x, y)
sub.plot(x, y2)
sub.plot(x, y3)
sub.set_xlabel('x', fontsize=14)
sub.set_ylabel('y', fontsize=14)
sub.set_title('Plot1', fontsize=15)
fig.suptitle(r'Plot 1', fontsize = 15)
sub.set_xticks([0, 0.5, 1.0])
sub.set_xticks(np.arange(0, 1.01, 0.1), minor=True)
sub.set_xticklabels(['a', 'b', 'c'])
plt.show()
plt.close()
代码我在本机跑过,但要主要的是不同的matplotlib版本,可能会导致一些差异。
我的版本是:
matplotlib==3.7.1
Python 3.10.6
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
# 绘制三条测试用的折线段
x = range(10)
y1 = [i**2 for i in x]
y2 = [2*i+1 for i in x]
y3 = [3*i-1 for i in x]
lines = plt.plot(x, y1, x, y2, x, y3)
# 创建checkbox
labels = ['segment 1', 'segment 2', 'segment 3']
states = [True, True, True]
ax_checkbox = plt.axes([0.15, 0.65, 0.18, 0.18], facecolor='lightgoldenrodyellow')
checkbox = CheckButtons(ax_checkbox, labels, states)
# checkbox的回调函数
def on_checkbox_clicked(label):
index = labels.index(label)
state = states[index]
states[index] = not state
line = lines[index]
line.set_visible(not state)
plt.draw()
for label in labels:
checkbox.on_clicked(on_checkbox_clicked)
plt.show()
```