如何在Matplotlib中显示堆叠水平条形图中的数据值

4

你好,我目前在使用数据框绘制堆叠水平条形图。以下是代码:

new_data.plot.barh(stacked = True)

我得到了下面这样的图表。

enter image description here

理想情况下,我希望数据值可以像下面这样显示在其中。 enter image description here 我该如何实现这一点?任何帮助都将不胜感激。谢谢。

考虑使用 Text:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.text.html - duncster94
1个回答

5

这里有一个类似的问题(链接),只需要使用ax.text命令,并根据每根柱子的值和编号调整x和y位置即可,例如:

import pandas as pd
df = pd.DataFrame({'value1':[10, 30, 20],'value2':[20,50,10]})
ax = df.plot.barh(stacked = True);
print(df)
for rowNum,row in df.iterrows():
    xpos = 0
    for val in row:
        xpos += val
        ax.text(xpos + 1, rowNum-0.05, str(val), color='black')
    xpos = 0
display(ax)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接