Reputation: 47
I am trying to plot a 2D array in 3D with python mplot3d however I am getting an error about incompatible dimensions on axis 1 I have looked at other questions where answers have suggested using meshgrid but I am already using that and still getting an error, my X and Y ranges also multiply to the number of Z values. here is my code:
def view_3d(map3d):
fig = plt.figure()
ax = fig.gca(projection='3d')
X = []
Y = []
Z = []
for wid in range(len(map3d)):
X.append(wid)
for hi in range(len(map3d[wid])):
if wid is 0:
Y.append(hi)
Z.append(map3d[wid][hi])
print(len(X), len(Y), len(Z))
X = np.array(X)
Y = np.array(Y)
X2, Y2 = np.meshgrid(X, Y)
Z = np.array(Z)
print(len(X2),len(Y2),len(Z))
print(len(X2[0]), len(Y2[0]))
surf = ax.plot_surface(X2, Y2, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
The passed 2d array (map3d) have lengths of 566-by-566
The print statements were just to confirm the lengths of the arrays
The error is:
Traceback (most recent call last):
File "__init__.py", line 199, in <module>
view_3d(map_results)
File "__init__.py", line 163, in view_3d
linewidth=0, antialiased=False)
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 1564, in plot_surface
X, Y, Z = np.broadcast_arrays(X, Y, Z)
File "C:\Python27\lib\site-packages\numpy\lib\stride_tricks.py", line 101, in broadcast_arrays
"incompatible dimensions on axis %r." % (axis,))
ValueError: shape mismatch: two or more arrays have incompatible dimensions on axis 1.
A google drive link to the code and images required to run the code and view the error is below: https://drive.google.com/folderview?id=0B2ssDQewnhReWGJZYXZRSXNxRFU&usp=sharing
All help is appreciated, Thanks
Upvotes: 2
Views: 2696
Reputation: 3363
Your Z
array must have the same shape as X2,Y2
in order plot_surface
to work.
So I changed the line
Z = np.array(Z)
to
Z = np.array(Z).reshape(Y.size,X.size)
and It worked!
Upvotes: 1