Matplotlib:堆积的条形图 [英] Matplotlib: Stacked Bar Graphs
本文介绍了Matplotlib:堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 matplotlib的堆叠条形图示例,其中有两个问题.你能帮我理解为什么我的代码没有适当地堆叠值吗?
I'm using matplotlib's stacked bar graph example with a couple of issues. Can you please help me understand why my code is not stacking the values appropriately?
N = 3
#('PledMis', 'PledFel', 'FoundFel')
Incarceration = (115.3, 1.99,23.7 )
Probation = (52.0, 45.9, 45.0)
Work = (0, 0.3, 2.4)
Program = (0, 0, 12)
ind = np.arange(N) # the x locations for the groups
width = 0.5 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, Incarceration, width, color='r')
p2 = plt.bar(ind, Probation, width, color='y',bottom=Incarceration)
p3 = plt.bar(ind, Work, width, color='b',bottom= Probation)
p4 = plt.bar(ind, Program, width, color='g',bottom=Work)
plt.ylabel('Months')
plt.title('Time')
plt.xticks(ind+width/2, ('Found Guilty: Felony', 'Pled Guilty: Mis', 'Pled Guilty: Felony' ) )
plt.yticks(np.arange(10,200,10))
plt.legend ((p1[0], p2[0], p3[0], p4[0]), ('Incarceration', 'Probation','Work','Program' ))
plt.show()
推荐答案
**您未考虑底部
的其他数据点.试试这个:
*you do not take the other data points into account for bottom
.
try this:
import numpy as np
N = 3
#('PledMis', 'PledFel', 'FoundFel')
Incarceration = np.array([115.3, 1.99,23.7] )
Probation = np.array([52.0, 45.9, 45.0])
Work = np.array([0, 0.3, 2.4])
Program = np.array([0, 0, 12])
ind = np.arange(N) # the x locations for the groups
width = 0.5 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, Incarceration, width, color='r')
p2 = plt.bar(ind, Probation, width, color='y',bottom=Incarceration)
p3 = plt.bar(ind, Work, width, color='b',bottom= Probation+Incarceration)
p4 = plt.bar(ind, Program, width, color='g',bottom=Work+Probation+Incarceration)
如果您要绘制多个条形图并希望将它们堆叠起来,那么使用循环并用自己的变量累加底部可能就足够了:
if you do multiple bar plots and want to stack them, it might be more sufficient to use a loop and accumulate the bottom with an own variable:
colors = ('r', 'y', 'b', 'g')
data = (Incarceration, Probation, Work, Program)
bottom = np.zeros(N)
for elem, color in zip(data, colors):
plt.bar(ind, elem, width, bottom=bottom, color=color)
bottom += elem
这篇关于Matplotlib:堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文