簡體   English   中英

如何使用 matplotlib 填充或遮蔽 Python 中堆疊條形圖中兩個對應點之間的區域?

[英]How to fill or shade area between two corresponding points in stacked bar plots in Python using matplotlib?

我有一個 dataframe df ,如下所示:

A   B
X   5   7
Y   10  5

df.to_dict()給出以下內容:

{'A': {'X': 5, 'Y': 10}, 'B': {'X': 7, 'Y': 5}}

我創建了一個堆疊條 plot 使用

df.plot(kind = "bar", stacked = True)

它看起來如下: 在此處輸入圖像描述

我想在 X 和 Y 條中對 A 之間的區域進行陰影處理,對於 B 也是如此。陰影區域反映了 A 和 B 的值在 X 和 Y 之間的變化情況。它應該看起來如下所示: 在此處輸入圖像描述

如何使用 Python 中的 matplotlib 填充這兩個堆疊條形圖之間的區域,保持條形 plot 的原始結構完好無損?

這是另一個使用更通用方法的 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)

Output:

在此處輸入圖像描述

這是一種使用fill_between的方法。

ax = df.plot(kind = "bar", stacked = True)
plt.fill_between(x = [ax.patches[0].get_x() + ax.patches[0].get_width(), 
                      ax.patches[1].get_x()], 
                 y1 = 0, 
                 y2 = [ax.patches[0].get_y() + ax.patches[0].get_height(),
                       ax.patches[1].get_y() + ax.patches[1].get_height()], 
                color = ax.patches[0].get_facecolor(), alpha=0.5)
plt.fill_between(x = [ax.patches[2].get_x() + ax.patches[2].get_width(), 
                      ax.patches[3].get_x()], 
                 y1 = [ax.patches[0].get_y() + ax.patches[0].get_height(),
                       ax.patches[1].get_y() + ax.patches[1].get_height()], 
                 y2 = [ax.patches[2].get_y() + ax.patches[2].get_height(),
                       ax.patches[3].get_y() + ax.patches[3].get_height()], 
                color = ax.patches[2].get_facecolor(), alpha=0.5)
plt.plot()

好的。 我自己找到了一種使用ax.fill_between()的簡單方法。 對於 x,我指定 [0.25, 0.75]。 0.25 是指 X 的柱的右邊緣,而 0.75 是指 Y 的柱的左邊緣。X 和 Y 的刻度在 X 軸上的位置分別為 0 和 1。

對於 y1 和 y2,我分別指定要填充的上下邊緣的 y 坐標。

 fig, ax = plt.subplots() ax = df.plot(kind = "bar", stacked = True, ax = ax, color = ["blue","orange"]) ax.fill_between(x =[0.25,0.75], y1 = [0, 0], y2 = [5, 10], color = "blue", alpha = 0.5) ax.fill_between(x =[0.25, 0.75], y1 = [5, 10], y2 = [12, 15], color = "orange", alpha = 0.5) plt.show()

我得到如圖所示的東西: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM