如何使用 Pandas 和 Matplotlib 繪製交替填充條形圖?


若要使用 Pandas 繪製交替填充條形圖,我們可以採取以下步驟 -

  • 設定圖形大小並調整子圖之間以及子圖周圍的填充。

  • 使用 Pandas 建立具有兩列的資料框。

  • 將座標軸作為子圖組排新增到當前圖形中。

  • 按名稱建立kind="bars"類繪製圖形。

  • 建立交替填充列表。

  • 使用bars.patches獲取條形補丁。

  • 迭代bars補丁並設定每個補丁的填充。

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

示例

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

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

df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
ax = plt.figure().add_subplot(111)
bars = df.plot(ax=ax, kind='bar')
hatches = ["*", "/", "o", "x"]

for patch in bars.patches:
   patch.set_hatch(hatches[np.random.randint(10)%len(hatches)])

plt.show()

輸出

更新於: 2021 年 6 月 3 日

1K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.