Matplotlib:堆积的条形图

嗨贡萨洛

我使用的是matplotlib的堆叠条形图示例,其中有两个问题。您能帮我理解为什么我的代码未正确堆叠值吗?

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

输出量

麦克诺

*您不考虑的其他数据点bottom尝试这个:

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)

如果您要绘制多个条形图并想要堆叠它们,那么使用循环并用自己的变量累加底部可能就足够了:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章