如何使用 matplotlib 在一個圖表中繪製多個水平條形圖?


要使用 matplotlib 在一個圖表中繪製多個水平條形圖,我們可以執行以下步驟 −

步驟

  • 匯入庫 pandas、matplotlib 和 numpy。

  • 設定圖形大小並調整子圖之間的間距和子圖周圍的間距。

  • 建立水平條形圖位置的陣列。

  • 初始化條形圖寬度的變數 width

  • 建立一個水平條形圖。

  • 設定 Y 軸刻度和刻度標籤,並設定一定的限制。

  • 在右上方的位置向圖中新增圖例。

  • 要顯示圖形,請使用 show() 方法。

示例

import pandas
import matplotlib.pyplot as plt
import numpy as np

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

# Array for horizontal bar's position
ind = np.array([0, 1, 2])

# Bar's width
width = 0.4

fig, ax = plt.subplots()

# Horizontal bar plot
ax.barh(ind, np.array([4, 3, 5]), width, color='orange', label='N')
ax.barh(ind + width, np.array([2, 5, 2]), width, color='blue', label='M')

# Set Y-axis ticks and ticklabels
ax.set(yticks=ind + width, yticklabels=np.array(['A', 'B', 'C']),
ylim=[2*width - 1, len(ind)])

# Legend at the upper right corner
ax.legend(loc='upper right')

# Display the plot
plt.show()

輸出

它將產生以下輸出 −

更新時間: 2022 年 2 月 1 日

3000+ 瀏覽量

開啟你的 職業之旅

完成課程後獲得認證

開始
廣告