Pandas bar 如何标记所需值

Iwi*_*ace 1 python matplotlib bar-chart pandas plot-annotations

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
Run Code Online (Sandbox Code Playgroud)

我有上面的数据框,并且我知道如何根据两列 A 和 B 绘制堆积条形图。 在此输入图像描述

如何在条形顶部添加值标签,例如对于 X=0,我想在蓝色条形上方标记 50(总数的 29.4%),在蓝色条形内的绿色条形上方标记 25(组中的 50%)酒吧。

任何帮助表示赞赏。

Joh*_*anC 5

第一个条形存储在 中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()
Run Code Online (Sandbox Code Playgroud)

带标签的 pandas 条形图

为了进一步强调这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)
Run Code Online (Sandbox Code Playgroud)

孵化B