在堆叠条形图的顶部显示总值

2024-04-19 17:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在堆叠条形图的顶部显示绘制的框的总值。 在方框图中进行这项工作非常简单,在matplotlib文档中是一个很好的例子,但是将条形图堆叠起来会很困难。你知道吗

在D3js中有很多问题和答案,但是matplotlib中没有,我想知道为什么会发生这种情况,因为堆叠条形图似乎经常用于数据可视化。你知道吗

我试着遵循这个:python - how to show values on top of bar plot

但是我的xlocs比我的情节要大。 例如:如果我把文本标在xlocs的索引0上,它就会把值标在图表左侧的外部。你知道吗

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()

编辑1 回答的代码对给定的数据集有效,但当我尝试更大的数据集时,值没有显示出来。你知道吗

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()

Tags: ofthe数据matplotlibshowbarpltwidth