如何在 Python 中使用 matplotlib 為子圖設定相同的比例?


要在 Python 中使用 matplotlib 為子圖設定相同的比例,我們可以採取以下步驟−

  • 設定圖形大小並調整子圖之間和周圍的填充。
  • 建立一個新圖形或啟用一個現有圖形。
  • 'ax1'新增到圖形中,作為子圖佈置的一部分,其中 nrows=2、ncols=1 和 index=1。
  • 將另一個軸 'ax2' 新增到圖形中,作為子圖佈置的一部分,其中 nrows=2、ncols=1 和 index=2,具有共享的 X 軸(為子圖設定相同的比例)
  • 建立"t"資料點,在軸 ax1 和 ax2 上繪製正弦和餘弦曲線。
  • 要顯示圖形,請使用show()方法。

示例

import matplotlib.pyplot as 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()

輸出

將產生以下輸出

更新時間:20-Sep-2021

3K+觀看

開創您的職業生涯

完成課程以獲得認證

開始體驗
廣告
© . All rights reserved.