我是Python新手。我一直在尝试绘制一个包含3列和1024个数据点的数据文件。运行代码时出现以下错误:
Traceback (most recent call last):
File "plot-data.py", line 27, in <module>
linewidth=0, antialiased=False)
File "/home/ritajit/.local/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1624, in plot_surface
X, Y, Z = np.broadcast_arrays(X, Y, Z)
File "/home/ritajit/.local/lib/python2.7/site-packages/numpy/lib/stride_tricks.py", line 249, in broadcast_arrays
shape = _broadcast_shape(*args)
File "/home/ritajit/.local/lib/python2.7/site-packages/numpy /lib/stride_tricks.py", line 184, in _broadcast_shape
b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape
我的代码看起来像这样
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.mlab import griddata
import matplotlib.cm as cm
from pylab import rcParams
rcParams['figure.figsize'] = 9, 9
## 3D surface_plot
fig = plt.figure()
axes = fig.add_subplot(111, projection='3d') #gca = get current axis
data = np.loadtxt('2D-data.txt')
x = data[:,0]
y = data[:,1]
z = data[:,2]
xi = np.unique(x)
yi = np.unique(y)
xv, yv = np.meshgrid(x,y)
Z = griddata(x, y, z, xi, yi, interp='linear')
# surface_plot with color grading and color bar
p = axes.plot_surface(xv,yv,Z, rstride=4, cstride=4, cmap=cm.RdBu,
linewidth=0, antialiased=False)
fig.colorbar(p, shrink=0.5)
axes.set_xlabel('$x$',fontsize=15)
axes.set_ylabel('$y$',fontsize=15)
axes.set_zlabel('$z$',fontsize=15)
plt.tight_layout()
fig.savefig("surface.pdf")
plt.show()
我无法解决这个问题
我做错了什么?
有没有其他方法可以绘制3d数据文件?
我的数据文件中的几行:
1 2 1.30884
2 2 1.30925
3 2 1.30974
4 2 1.30841
5 2 1.30864
6 2 1.30795
第1列,第2列,第3列分别为x,y,z
答案 0 :(得分:0)
这里有三个主要问题:
您需要对唯一值进行meshgrid,而不是原始值
xi = np.unique(x)
yi = np.unique(y)
xv, yv = np.meshgrid(xi,yi)
您需要对网格值进行插值
griddata(x, y, z, xv, yv)
您需要绘制Z
,而不是z
p = axes.plot_surface(xv,yv,Z)
总的来说,看起来你可以通过重塑数据列来实现几乎相同(但是小数据摘录不足以判断这一点)。
最后,matplotlib.mlab.griddata
将在下一个版本中弃用。作为替代方案,考虑scipy.interpolate.griddata
。另请查看Contour plot of irregularly spaced data示例。