我有一個df如下所示的資料框:
A B
X 5 7
Y 10 5
df.to_dict() 給出以下內容:
{'A': {'X': 5, 'Y': 10}, 'B': {'X': 7, 'Y': 5}}
我創建了一個堆疊條形圖
df.plot(kind = "bar", stacked = True)
它看起來如下:

我想對 X 和 Y 條中的 A 之間的區域進行陰影處理,對于 B 也是如此。陰影區域反映了 A 和 B 的值在 X 和 Y 之間的變化情況。它應該如下所示:

如何在 Python 中使用 matplotlib 填充這兩個堆疊條形圖之間的區域,保持條形圖的原始結構完整?
uj5u.com熱心網友回復:
這是另一個使用更通用方法的 fill_between :
# loop through the bars to get the bottom and top points
bottoms = []
tops = []
for patch in ax.patches:
x,y = patch.get_xy()
w,h = patch.get_width(), patch.get_height()
bottoms = [(x,y), (x w, y)]
tops = [(x, y h), (x w, y h)]
# convert to numpy for easy slicing
tops = np.array(tops)
bottoms = np.array(bottoms)
# extract the x coordinates
x = np.unique(bottoms[:,0])
num_x = len(x)
# fill between each bottom and top pairs
for i in range(0, len(bottoms), num_x):
plt.fill_between(x, tops[i:i num_x, 1], bottoms[i:i num_x, 1], alpha=0.5)
輸出:

uj5u.com熱心網友回復:
這是一種使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383670.html
標籤:Python 蟒蛇-3.x 熊猫 matplotlib 条形图
上一篇:pipinstall在Dockerfile中失敗,但在Container中是可能的
下一篇:添加誤差線時如何注釋條形圖
