d = {'X':[1,2,3,4],'A': [50,40,20,60], '% of Total in A':[29.4,23.5,11.8,35.3] , 'B': [25,10,5,15], '% in A' :[50,25,25,25]}
df = pd.DataFrame(d)
ax = df.plot(x='X',y="A", kind="bar")
df.plot(x='X', y="B", kind="bar", ax=ax,color='C2')
X A % of Total in A B % in A
0 1 50 29.4 25 50
1 2 40 23.5 10 25
2 3 20 11.8 5 25
3 4 60 35.3 15 25
我有上面的資料框,我知道如何根據兩列 A 和 B 繪制堆積條形圖。

如何在條形頂部添加值標簽,例如 X=0,我想在藍色條形上方標記 50(總數的 29.4%),在藍色條形內的綠色條形上方標記 25(組中的 50%)酒吧。
任何幫助表示贊賞。
uj5u.com熱心網友回復:
第一個條形存盤在 中ax.containers[0],第二個在 中ax.containers[1]。您可以ax.bar_label(...)將這些容器與相應標簽的串列一起使用。
順便說一句,您x=在第二個條形圖中丟失了。
from matplotlib import pyplot as plt
import pandas as pd
d = {'X': [1, 2, 3, 4], 'A': [50, 40, 20, 60], '% of Total in A': [29.4, 23.5, 11.8, 35.3], 'B': [25, 10, 5, 15], '% in A': [50, 25, 25, 25]}
df = pd.DataFrame(d)
ax = df.plot(x='X', y="A", kind="bar")
df.plot(x='X', y="B", kind="bar", color='C2', ax=ax)
ax.bar_label(ax.containers[0], labels=df['% of Total in A'])
ax.bar_label(ax.containers[1], labels=df['% in A'], color='white')
plt.show()

為了進一步強調它B是 的一部分A,你可以給它們相同的顏色,然后孵化B。例如:
ax = df.plot(x='X', y="A", kind="bar", color='dodgerblue')
df.plot(x='X', y="B", kind="bar", facecolor='dodgerblue', hatch='xx', rot=0, ax=ax)
ax.bar_label(ax.containers[0], labels=[f'{p} %' for p in df['% of Total in A']])
ax.bar_label(ax.containers[1], labels=[f'{p} %' for p in df['% in A']], color='white')
for spine in ['top', 'right']:
ax.spines[spine].set_visible(False)

uj5u.com熱心網友回復:
- 鋼筋未正確堆疊。補丁按 z 順序堆疊,而不是垂直(y 順序)。另外,x 軸不正確,因為
x='X'第二個圖中缺少。 - 用
zip結合的containers和cols,然后通過自定義labels的labels=引數。 - 另請參閱
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374548.html標籤:Python 熊猫 matplotlib 注释 条形图
