📅  最后修改于: 2023-12-03 15:07:44.345000             🧑  作者: Mango
有时候,我们需要在 Matplotlib 图的左侧和右侧同时绘制两个不同的 y 轴,以在同一张图中比较不同的数据。本文将介绍如何实现这一目标。
首先,我们需要导入 numpy
和 matplotlib
库:
import numpy as np
import matplotlib.pyplot as plt
然后,我们定义两个数列,分别代表两组数据:
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.exp(x)
接着,我们可以使用 twinx()
和 twiny()
方法创建两个子图,分别对应于左侧和右侧的 y 轴和顶部和底部的 x 轴。然后,我们将数据绘制到各自的子图中:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twiny()
ax1.plot(x, y1, 'r-', label='sin(x)')
ax2.plot(x, y2, 'b-', label='exp(x)')
ax1.set_xlabel('X data')
ax1.set_ylabel('sin(x)', color='r')
ax2.set_ylabel('exp(x)', color='b')
ax3.set_xlim(ax1.get_xlim())
ax3.set_xlabel('Y data')
plt.legend(loc='upper right')
plt.show()
最后,我们将左侧 y 轴的标签颜色设置为红色,右侧 y 轴的标签颜色设置为蓝色,并且通过 get_xlim()
方法将左侧和右侧的 x 轴范围设置为相同。
完整代码如下:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.exp(x)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twiny()
ax1.plot(x, y1, 'r-', label='sin(x)')
ax2.plot(x, y2, 'b-', label='exp(x)')
ax1.set_xlabel('X data')
ax1.set_ylabel('sin(x)', color='r')
ax2.set_ylabel('exp(x)', color='b')
ax3.set_xlim(ax1.get_xlim())
ax3.set_xlabel('Y data')
plt.legend(loc='upper right')
plt.show()
输出结果如下:
我们可以看到,左侧 y 轴对应的是红色曲线,右侧 y 轴对应的是蓝色曲线,两组数据同时显示在同一张图中。