gpt4 book ai didi

Matplotlib:堆叠条形图

转载 作者:行者123 更新时间:2023-12-02 01:03:57 26 4
gpt4 key购买 nike

我正在使用 matplotlib's stacked bar graph example有几个问题。你能帮我理解为什么我的代码没有正确地堆叠值吗?

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

Output

最佳答案

*您不考虑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

关于Matplotlib:堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24852852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com