我给了一些州名称,它们的未结和已结投诉总数都存储在列表中。
我想绘制一个堆叠的条形图,在x轴上显示状态,其中每个状态的条形图以堆叠形式显示打开和关闭的投诉。我自己尝试过,但是不断出错,
shape mismatch: objects cannot be broadcast to a single shape
这是我正在使用的代码
# plotting stack bar chart
indx = list(range(len(states)))
plt.figure(figsize=(12,8))
graph_state = plt.bar(x=indx, height=states, width=0.35)
graph_closed = plt.bar(x=indx, height=closed, width=0.35, bottom=states)
graph_opened = plt.bar(x=indx, height=opened, width = 0.35, bottom=closed+states)
plt.xlabel('States')
plt.ylabel('Complaints')
plt.show()
这是我使用的数据
states = ['Maryland','Georgia','Michigan','California','NewMexico','Indiana','Virginia','Illinois','Pennsylvania','Massachusetts','Oregon','Texas','NewHampshire','Minnesota','Tennessee','Colorado','Florida','Alabama','Washington','NewYork','NewJersey','Maine','Missouri','WestVirginia','Montana','Mississippi','Connecticut','Vermont','Kentucky','SouthCarolina','Ohio','Utah','Delaware','Arkansas','Nevada','Louisiana','Kansas','Arizona','North Carolina','Rhode Island','District Of Columbia','District of Columbia','Iowa']
opened = [15,80,23,61,4,9,11,29,20,11,13,22,4,4,47,22,39,9,23,19,2,1,3,16,3,1,3,3,6,4,1,1,6,2]
closed = [63,208,92,159,11,50,49,135,110,50,36,49,8,29,96,58,201,17,75,6,56,3,3,8,1,23,9,2,4,15,3,16,8,6,1,12,1,14,3,1,14,1,1]
答案 0 :(得分:0)
如果我将“打开的”列表填充为与“状态”和“关闭的”长度相同的长度(43),则可以使绘图工作
import matplotlib.pyplot as plt
states = ['Maryland','Georgia','Michigan','California','NewMexico','Indiana','Virginia','Illinois','Pennsylvania','Massachusetts','Oregon','Texas','NewHampshire','Minnesota','Tennessee','Colorado','Florida','Alabama','Washington','NewYork','NewJersey','Maine','Missouri','WestVirginia','Montana','Mississippi','Connecticut','Vermont','Kentucky','SouthCarolina','Ohio','Utah','Delaware','Arkansas','Nevada','Louisiana','Kansas','Arizona','North Carolina','Rhode Island','District Of Columbia','District of Columbia','Iowa']
opened = [15,80,23,61,4,9,11,29,20,11,13,22,4,4,47,22,39,9,23,19,2,1,3,16,3,1,3,3,6,4,1,1,6,2,0,0,0,0,0,0,0,0,0]
closed = [63,208,92,159,11,50,49,135,110,50,36,49,8,29,96,58,201,17,75,6,56,3,3,8,1,23,9,2,4,15,3,16,8,6,1,12,1,14,3,1,14,1,1]
indx = list(range(len(states)))
width = 0.35
p1 = plt.bar(indx, opened, width)
p2 = plt.bar(indx, closed, width,
bottom=opened)
plt.ylabel('opened')
plt.xticks(indx, states, rotation=90)
plt.tight_layout()
plt.show()