以下是修改后的代码,实现了将上下两个折线图画在同一张图上:

import matplotlib.pyplot as plt

# 上图数据
x1 = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
y11 = [10, 15, 20, 25, 30, 35]
y21 = [5, 10, 15, 20, 25, 30]
annotations1 = [('Jan', 10, 5), ('Mar', 20, 15), ('May', 30, 25)]

# 下图数据
x2 = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
y12 = [40, 45, 50, 55, 60, 65]
y22 = [35, 40, 45, 50, 55, 60]
annotations2 = [('Jul', 40, 35), ('Sep', 50, 45), ('Nov', 60, 55)]

# 绘制图形
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# 绘制上图
ax1.plot(x1, y11, color='blue', label='y1')
ax2.plot(x1, y21, color='green', label='y2')
for annotation in annotations1:
    ax1.scatter(annotation[0], annotation[1], color='red', s=50, zorder=3)
    ax2.scatter(annotation[0], annotation[2], color='red', s=50, zorder=3)

# 绘制下图
ax1.plot(x2, y12, color='orange', label='y3')
ax2.plot(x2, y22, color='purple', label='y4')
for annotation in annotations2:
    ax1.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/y3')
ax2.set_ylabel('y2/y4')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')

# 展示图形
plt.show()

在该代码中,首先定义了上下两个折线图的数据和标注点列表,然后使用plt.subplots()创建了一个包含两个子图(即上下两个折线图)的图形。接着使用ax1.plot()ax2.plot()分别绘制了两个y轴的折线图,使用ax1.scatter()ax2.scatter()在标注点处画出了红色的点。最后使用ax1.set_xlabel()ax1.set_ylabel()ax2.set_ylabel()设置了x轴和y轴的标签,使用ax1.legend()ax2.legend()设置了上下两个图例的位置。

Python 画双 Y 轴折线图:上下两个图合并,带标注点放大

原文地址: https://www.cveoy.top/t/topic/nBII 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录