我有一个分析数据集然后输出xyz数据的脚本。为了理解数据的分布,我想在3d图中将其可视化。由于我没有使用matplotlib的经验,我只是复制了here中的代码,并期望它与my text file一起使用,如下所示:
-0.9 -0.9 483
-0.9 -0.7 224
-0.9 -0.5 156
-0.9 -0.3 153
-0.9 -0.1 174
-0.9 0.1 268
-0.9 0.3 95
-0.9 0.5 59
-0.9 0.7 50
-0.9 0.9 199
-0.7 -0.9 917
-0.7 -0.7 244
-0.7 -0.5 208
-0.7 -0.3 148
-0.7 -0.1 139
-0.7 0.1 98
-0.7 0.3 52
-0.7 0.5 56
-0.7 0.7 60
-0.7 0.9 221
...
然而,一旦我启动脚本,我收到以下错误,导致颜色栏显示不正确:
Warning (from warnings module):
File "C:\Program Files\Python35\lib\site-packages\matplotlib\colors.py", line 496
cbook._putmask(xa, xa < 0.0, -1)
RuntimeWarning: invalid value encountered in less
此外,绘图的边缘有这些三角形。我不确定它们是否也是上述错误的结果。 这是输出:
这是我的代码:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
data = np.genfromtxt('plot.txt')
x = data[:,0]
y = data[:,1]
z = data[:,2]
xi = np.linspace(-1, 1)
yi = np.linspace(-1, 1)
X, Y = np.meshgrid(xi, yi)
Z = griddata(x, y, z, xi, yi, interp='linear')
surf = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap=cm.jet,
linewidth=1, antialiased=True)
ax.set_zlim3d(np.min(Z), np.max(Z))
fig.colorbar(surf)
plt.show()
编辑1: 我编辑了源代码,在违规行之前打印xa,输出:
[ nan nan nan nan nan nan nan nan nan nan nan 256.
256. 256. 256. 256. 256. 256. 256. nan nan 256. 256. 256.
256. 256. 256. 256. 256. nan nan 256. 256. 256. 256. 256.
256. 256. 256. nan nan 256. 256. 256. 256. 256. 256. 256.
256. nan nan 256. 256. 256. 256. 256. 256. 256. 256. nan
nan 256. 256. 256. 256. 256. 256. 256. 256. nan nan 256.
256. 256. 256. 256. 256. 256. 256. nan nan 256. 256. 256.
256. 256. 256. 256. 256. nan nan nan nan nan nan nan
nan nan nan nan]
所以我在这里显然有一些NaN值,但我不确定它们来自哪里。
答案 0 :(得分:1)
问题是griddata
无法生成网格边缘的数据。这通过屏蔽输出数组在内部避开。但是,对于屏蔽数组,无法进行确定颜色所需的比较xa < 0
。
这里的解决方案是从绘图中排除边缘。
ax.plot_surface(X[1:-1,1:-1], Y[1:-1,1:-1], Z[1:-1,1:-1])
完整示例:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
data = np.genfromtxt('plot.txt')
x = data[:,0]
y = data[:,1]
z = data[:,2]
xi = np.linspace(-1, 1)
yi = np.linspace(-1, 1)
X, Y = np.meshgrid(xi, yi)
Z = griddata(x, y, z, xi, yi, interp='linear')
surf = ax.plot_surface(X[1:-1,1:-1], Y[1:-1,1:-1], Z[1:-1,1:-1],
rstride=5, cstride=5, cmap=cm.jet,
linewidth=1, antialiased=True)
ax.set_zlim3d(np.min(Z), np.max(Z))
fig.colorbar(surf)
plt.show()