Python绘制上下两张折线图,每个图拥有两个Y轴并标注关键点
以下是修改后的代码,实现了将上下两个折线图画在同一张图上:
import matplotlib.pyplot as plt
# 上图数据
x = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
y1 = [10, 15, 20, 25, 30, 35]
y2 = [5, 10, 15, 20, 25, 30]
annotations1 = [('Jan', 10, 5), ('Mar', 20, 15), ('May', 30, 25)]
# 下图数据
y3 = [40, 45, 50, 55, 60, 65]
y4 = [35, 40, 45, 50, 55, 60]
annotations2 = [('Jul', 40, 35), ('Sep', 50, 45), ('Nov', 60, 55)]
# 绘制图形
fig, ax1 = plt.subplots()
# 绘制上图
ax1.plot(x, y1, color='blue', label='y1')
ax1.plot(x, y2, color='green', label='y2')
for annotation in annotations1:
ax1.scatter(annotation[0], annotation[1], color='red', s=50, zorder=3)
ax1.scatter(annotation[0], annotation[2], color='red', s=50, zorder=3)
# 绘制下图
ax2 = ax1.twinx()
ax2.plot(x, y3, color='orange', label='y3')
ax2.plot(x, y4, color='purple', label='y4')
for annotation in annotations2:
ax2.scatter(annotation[0], annotation[1], color='red', s=50, zorder=3)
ax2.scatter(annotation[0], annotation[2], color='red', s=50, zorder=3)
# 图形设置
ax1.set_xlabel('Month')
ax1.set_ylabel('y1/y2')
ax2.set_ylabel('y3/y4')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
# 展示图形
plt.show()
在该代码中,首先定义了上下两个折线图的数据和标注点列表,然后使用plt.subplots()创建了一个包含两个子图(即上下两个折线图)的图形。接着使用ax1.plot()和ax1.plot()在同一个子图上绘制了两个y轴的折线图,使用ax1.scatter()在标注点处画出了红色的点。下图中,使用ax1.twinx()创建了第二个y轴,使用ax2.plot()和ax2.plot()在第二个子图上分别绘制了两个y轴的折线图,使用ax2.scatter()在标注点处画出了红色的点。最后使用ax1.set_xlabel()、ax1.set_ylabel()和ax2.set_ylabel()设置了x轴和y轴的标签,使用ax1.legend()和ax2.legend()设置了上下两个图例的位置。
原文地址: https://www.cveoy.top/t/topic/nBIV 著作权归作者所有。请勿转载和采集!