在 Python Matplotlib 中繪製共用相同 Y 軸的兩張水平條形圖


要繪製共用相同 Y 軸的兩張水平條形圖,我們可以在subplot()方法中使用sharey=ax1,對於水平條形圖,我們可使用barh()方法。

步驟

  • 為資料點建立列表。
  • 使用figure()方法建立一個新圖形或者啟用一個現有圖形。
  • 使用subplot()方法將子圖新增到當前圖形,索引為1
  • 使用barh()方法在軸 1 上繪製水平條形圖。
  • 使用subplot()方法將子圖新增到當前圖形,索引為2。共享軸 1 的 Y 軸。
  • 在軸 2 上繪製水平條形圖。
  • 要顯示圖形,請使用show()方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

y = [3, 1, 5]
x1 = [10, 7, 3]
x2 = [9, 5, 1]

fig = plt.figure()

axe1 = plt.subplot(121)
axe1.barh(y, x1, align='center', color='red', edgecolor='black')

axe2 = plt.subplot(122, sharey=axe1)
axe2.barh(y, x2, align='center', color='green', edgecolor='black')

plt.show()

輸出

更新時間:05-6 月-2021

952 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.