以下是一个示例代码,使用 matplotlib 库画出上下两个折线图,其中第一个图有两个 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]
annotations = [('Jan', 10, 5), ('Mar', 20, 15), ('May', 30, 25)]

# 绘制上图
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, color='blue', label='y1')
ax2.plot(x, y2, color='green', label='y2')
for annotation in annotations:
    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.legend(loc='upper left')
ax2.legend(loc='upper right')

# 下图数据
x = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
y1 = [40, 45, 50, 55, 60, 65]
y2 = [35, 40, 45, 50, 55, 60]

# 绘制下图
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, color='blue', label='y1')
ax2.plot(x, y2, color='green', label='y2')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')

# 展示图形
plt.show()

上图中,使用 ax1.twinx() 创建了第二个 y 轴,使用 ax1.plot()ax2.plot() 分别绘制了两个 y 轴的折线图,使用 ax1.scatter()ax2.scatter() 在标注点处画出了红色的点。下图与上图类似,只需要更改数据即可。

Python Matplotlib: 双Y轴折线图绘制及标注点放大

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

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