如何在 Matplotlib 中添加第二个 X 轴?

matplotlibserver side programmingprogramming更新于 2025/5/10 13:37:17

我们可以使用 twiny() 方法创建第二个 X 轴。类似地,使用 twinx,我们可以创建一个共享的 Y 轴。

步骤

  • 使用 subplots 方法创建 fig 和 ax 变量,其中默认 nrows 和 ncols 为 1。

  • 使用传入 plot() 方法参数的列表绘制线条,颜色为"red"。

  • 创建一个共享 Y 轴但独立 X 轴的 Axes 孪生。

  • 在步骤 3 中创建的 ax2 上绘制线条。

  • 调整子图之间和周围的填充。

  • 要显示图形,请使用 plt.show() 方法。

示例

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot([1, 2, 3, 4, 5], [3, 5, 7, 1, 9], color='red')
ax2 = ax1.twiny()
ax2.plot([11, 12, 31, 41, 15], [13, 51, 17, 11, 76], color='blue')
fig.tight_layout()
plt.show()

输出


相关文章