import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# create some sample data
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
z1 = np.array([1, 2, 3])
z2 = np.array([4, 5, 6])
z3 = np.array([7, 8, 9])
color1 = np.array(['r', 'g', 'b'])
color2 = np.array(['y', 'm', 'c'])
# create a figure and a set of subplots
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# plot the first set of bars
for i in range(len(x)):
ax.bar(x[i], z1[i], y[i], zdir='y', color=color1[i], alpha=0.8)
ax.bar(x[i], z1[i] - z1[i], y[i], zdir='y', color=color2[i], alpha=0.8)
# plot the second set of bars
for i in range(len(x)):
ax.bar(x[i], z2[i], y[i]+0.5, zdir='y', color=color1[i], alpha=0.8)
ax.bar(x[i], z2[i] - z2[i], y[i]+0.5, zdir='y', color=color2[i], alpha=0.8)
# plot the third set of bars
for i in range(len(x)):
ax.bar(x[i], z3[i], y[i]+1.0, zdir='y', color=color1[i], alpha=0.8)
ax.bar(x[i], z3[i] - z3[i], y[i]+1.0, zdir='y', color=color2[i], alpha=0.8)
# set the axis labels and title
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
ax.set_title('3D Bar Chart')
# show the plot
plt.show()
Running this code in VSCode on Windows 11 (Python 3.10) results in the following error:
Traceback (most recent call last): File "c:\Users\16168\Documents\delta-scan-master\delta-scan-master\test\eval_test_display.py", line 73, in ax.bar(x[i], z1[i], y[i], zdir='y', color=color1[i], alpha=0.8) File "C:\Users\16168\Documents\delta-scan-master\delta-scan-master\env\lib\site-packages\matplotlib_init_.py", line 1459, in inner return func(ax, *map(sanitize_sequence, args), **kwargs) File "C:\Users\16168\Documents\delta-scan-master\delta-scan-master\env\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 2318, in bar zs = np.broadcast_to(zs, len(left)) TypeError: object of type 'numpy.int32' has no len()
I'm trying to create a set of 3d bar charts where each bar chart is bicolored (representing two different values along the vertical axis). I don't understand why the error is in line 73, rather than 72 where the len() function appears. I read the error as essentially saying that I'm calling the length function on an integer data type - but x is (should be?) a numpy array as declared above. Any ideas? Or is there a mismatch between the type of i and the type returned by len(x)?
1条答案
按热度按时间trnvg8h31#
ax.bar()
调用说明,但所有其他调用都会出现错误。*我不明白为什么错误出现在第73行,而不是len()函数出现的第72行。
错误确实不在
for i in range(len(x))
上,而是在ax.bar()
调用上。Axes3D.bar
需要一个x
、y
和z
值的列表,但您传递的是单个标量值x[i]
、z[i]
和y[i]
。代替for循环,您可以直接传递值列表(
color
也是如此)。它将为每个i
创建一个条形图。补充说明:
ax.bar3d
ax.bar
调用中,作为第二个参数zX - zX
传递,这可能是错误的(0高度条形图;不可见)。修复
ax.bar()
调用,这是您的图目前的样子: