如何使用 Matplotlib 在 Python 中为子图设置相同的比例?

要使用 Matplotlib 在 Python 中为子图设置相同的比例,我们可以采取以下步骤 -

  • 设置图形大小并调整子图之间和周围的填充。

  • 创建新地物或激活现有地物。

  • “ax1”添加到图中,作为 nrows=2、ncols=1 和 index=1 的子图排列的一部分。

  • 在图中添加另一个轴“ax2”作为子图排列的一部分,nrows=2,ncols=1 和索引=2,共享 X 轴(为子图设置相同的比例)

  • 创建“t”数据点以在轴 ax1 和 ax2 上绘制正弦和余弦曲线。

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

示例

importmatplotlib.pyplotas plt
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Plot the figure
fig = plt.figure()

# Add the axes
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

# Create data points
t = np.linspace(-5, 5, 100)

# Plot sine and cosine curves on ax1 and ax2
ax1.plot(t, np.sin(2 *np.pi* t), color='red', lw=4)
ax2.plot(t, np.cos(2 *np.pi* t), color='orange', lw=4)

plt.show()
输出结果

它将产生以下输出