python传入数据使用plt方法和for循环生成多个Y轴的折线图
下面是一个示例代码,演示如何使用plt方法和for循环生成多个Y轴的折线图:
import matplotlib.pyplot as plt
# 定义X轴数据
x = [1, 2, 3, 4, 5]
# 定义Y轴数据
y_list = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15]]
# 创建子图
fig, ax1 = plt.subplots()
# 循环生成多个Y轴的折线图
for y in y_list:
ax1.plot(x, y, marker='o')
# 设置Y轴标签
ax1.set_ylabel('Y1')
# 添加第二个Y轴
ax2 = ax1.twinx()
# 添加第二个Y轴的数据
y2 = [6, 7, 8, 9, 10]
ax2.plot(x, y2, color='r', linestyle='--', marker='s')
# 设置第二个Y轴的标签
ax2.set_ylabel('Y2', color='r')
# 显示图例
ax1.legend(['Y1'], loc='upper left')
ax2.legend(['Y2'], loc='upper right')
# 设置X轴标签
plt.xlabel('X')
# 显示图形
plt.show()
运行这段代码,将会生成一个包含两个Y轴的折线图。其中,Y1轴的数据用蓝色的实线表示,Y2轴的数据用红色的虚线表示
原文地址: https://www.cveoy.top/t/topic/hQ3m 著作权归作者所有。请勿转载和采集!