【发布时间】:2021-01-23 13:04:40
【问题描述】:
我正在尝试使用 matplotlib 绘制条形图,但它向我显示了此错误消息 ValueError:形状不匹配:无法将对象广播到单个形状
这是我的代码:
print(lol)
X = numpy.arange(3)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, lol[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, lol[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, lol[2], color = 'r', width = 0.25)
plt.show()
这是我的错误信息输出:
这里的数据是需要在条形图中绘制的数据
它以list 的list 的形式存储在lol 中。
[[0, 21, 0, 15, 0, 4, 11, 0, 1, 0, 0, 3, 32, 0, 0, 38, 0, 0, 0, 0, 2, 4, 4, 0, 4, 2, 0, 0, 1, 0, 1, 0, 0, 3, 1, 11, 0, 3, 10, 0, 1, 0, 0, 11, 0, 7, 0, 7, 0, 0, 7, 3, 2, 1, 1, 0, 1, 5, 1, 3, 1, 1, 4, 0, 2, 4, 0, 1, 5, 0, 0, 4, 2, 3, 1, 1, 0, 1, 0, 4, 1, 1, 9, 1, 6, 3, 7, 3, 0, 2, 0, 1, 1, 1, 5, 2, 3, 0, 1], [135, 0, 135, 0, 135, 0, 0, 135, 0, 135, 135, 0, 0, 135, 135, 0, 135, 135, 135, 135, 0, 0, 0, 135, 0, 0, 135, 135, 0, 135, 0, 135, 135, 0, 0, 0, 135, 0, 0, 135, 0, 135, 135, 0, 135, 0, 135, 0, 135, 135, 0, 0, 0, 0, 0, 135, 0, 0, 0, 0, 0, 0, 0, 135, 0, 0, 135, 0, 0, 135, 135, 0, 0, 0, 0, 0, 135, 0, 135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135, 0, 135, 0, 0, 0, 0, 0, 0, 135, 0], [143, 0, 143, 0, 143, 0, 0, 143, 0, 143, 143, 0, 0, 143, 143, 0, 143, 143, 143, 143, 0, 0, 0, 143, 0, 0, 143, 143, 0, 143, 0, 143, 143, 0, 0, 0, 143, 0, 0, 143, 0, 143, 143, 0, 143, 0, 143, 0, 143, 143, 0, 0, 0, 0, 0, 143, 0, 0, 0, 0, 0, 0, 0, 143, 0, 0, 143, 0, 0, 143, 143, 0, 0, 0, 0, 0, 143, 0, 143, 0, 0, 0, 0, 0, 0, 0, 0, 0, 143, 0, 143, 0, 0, 0, 0, 0, 0, 143, 0]]
错误:
Traceback (most recent call last):
File "E:\Pyton Excel Extractions\dashboard.py", line 68, in <module>
ax.bar(X + 0.00, lol[0], color = 'b', width = 0.25)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\__init__.py", line 1438, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_axes.py", line 2430, in bar
x, height, width, y, linewidth = np.broadcast_arrays(
File "<__array_function__ internals>", line 5, in broadcast_arrays
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\stride_tricks.py", line 258, in broadcast_arrays
shape = _broadcast_shape(*args)
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\stride_tricks.py", line 189, in _broadcast_shape
b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape
帮帮我!
【问题讨论】:
-
你想通过
arange(3)实现什么?X和lol[0]的长度不一样。 -
过段时间我会试一试的。
-
stackoverflow.com/questions/64279766/…这个@Grayrigel
标签: python numpy matplotlib bar-chart