如何使用Python绘制多条y轴范围不同的曲线,然后把它们合并在一张图上显示
import matplotlib.pyplot as plt
import numpy as np
def multilines(target, x, ys, types, colors, x_label, labels):
"""
用来绘制多条y轴范围不同的线,并在一张图上显示
"""
twins = []
twins.append(target[0])
p = []
for i in range(len(ys) - 1):
twins.append(target[0].twinx())
for i, label in enumerate(labels):
temp_p, = twins[i].plot(x, ys[i], types[i], color=colors[i], label=label)
p.append(temp_p)
twins[0].set_xlabel(x_label)
pad = 0
twin_lines = []
twin_labels = []
for i, twin in enumerate(twins):
twin.set_ylabel(labels[i])
twin.yaxis.set_label_position('left')
twin.yaxis.set_ticks_position('left')
twin.yaxis.label.set_color(p[i].get_color())
twin.tick_params(axis='y', colors=p[i].get_color(), pad=pad)
pad += 60
temp_line, temp_label = twin.get_legend_handles_labels()
twin_lines.append(temp_line)
twin_labels.append(temp_label)
final_line = twin_lines[0]
final_label = twin_labels[0]
for i in range(len(twin_lines) - 1):
final_line += twin_lines[i + 1]
final_label += twin_labels[i + 1]
twins[0].legend(final_line, final_label, loc='best')
if __name__ == '__main__':
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = 2 * np.cos(x)
y3 = 0.5 * np.tan(x)
fig, ax = plt.subplots(figsize=(16, 4), dpi=200)
fig.subplots_adjust(left=0.2)
multilines([ax], x, [y1, y2, y3], ['r-', 'b-', 'g-'], ['red', 'blue', 'green'], 'depth', ['y1', 'y2', 'y3'])
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/d43c589632514a7786a5245ca82912c5.png)