繁体   English   中英

在堆积条的顶部显示总值

[英]Display in top of the stacked bar the total value

我想在堆积条形图的顶部显示绘制的框的总值。 在 plot 框中进行操作非常简单,matplotlib 文档中有很好的示例,但堆叠条形使其变得困难。

有很多关于在 D3js 中执行此操作的问题和答案,但 matplotlib 上没有,我想知道为什么会发生这种情况,因为堆叠条 plot 似乎经常用于数据可视化。

我试图遵循这个: python - 如何在条形图 plot 顶部显示值

但我的xlocs比我拥有的地块大。 例如:如果我在 xlocs 的索引 0 上绘制文本,它将 plot 外部的值,在图表的左侧。

vl1 = [20,30] # low values
vl2 = [30,15] # up values
total = [50,45] # total

ind = np.arange(2)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, vl1, width)
p2 = plt.bar(ind, vl2, width, bottom=vl1)

plt.show()

EDIT1回答的代码适用于给定的数据集,但是当我尝试更大的数据集时,该值没有显示出来。

vl1 = [39000,60000] # low values
vl2 = [100000,70000] # up values
total = [139000,130000] # total

ind = np.arange(2)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, vl1, width)
p2 = plt.bar(ind, vl2, width, bottom=vl1)

plt.show()

您已经有了条形的总高度,因此只需遍历它们并annotate

vl1 = [20,30] # low values
vl2 = [30,15] # up values
total = [50,45] # total

ind = np.arange(2)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

fig, ax = plt.subplots()
p1 = ax.bar(ind, vl1, width)
p2 = ax.bar(ind, vl2, width, bottom=vl1)

for num, i in enumerate(total):
    ax.annotate(i, (num, i+1), ha='center', va='center')

plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM