我想使用matplotlib.pyplot.pcolormesh绘制深度图。
我拥有的是xyz文件 三列即x(lat),y(lon),z(dep)。
所有列长度相等
pcolormesh需要矩阵作为输入。 所以使用numpy.meshgrid我可以将x和y转换为矩阵:
xx,yy = numpy.meshgrid(x_data,y_data)
这很好......但是,我不知道如何创建我的深度(z)数据的矩阵...... 如何为我的z_data创建一个与我的x_data和y_data矩阵对应的矩阵?
答案 0 :(得分:4)
根据您是否生成z
,您至少有两种选择。
如果你正在生成z
(例如,你知道它的公式),这很容易(请参阅下面的method_1()
)。
如果您只是一个(x
,y
,z
)元组的列表,那就更难了(请参阅下面的method_2()
,也许{ {1}})。
<强>常量强>
method_3()
方法1:生成# min_? is minimum bound, max_? is maximum bound,
# dim_? is the granularity in that direction
min_x, max_x, dim_x = (-10, 10, 100)
min_y, max_y, dim_y = (-10, 10, 100)
z
生成以下图表:
这相对简单,因为您可以在任何您想要的点生成# Method 1:
# This works if you are generating z, given (x,y)
def method_1():
x = np.linspace(min_x, max_x, dim_x)
y = np.linspace(min_y, max_y, dim_y)
X,Y = np.meshgrid(x,y)
def z_function(x,y):
return math.sqrt(x**2 + y**2)
z = np.array([z_function(x,y) for (x,y) in zip(np.ravel(X), np.ravel(Y))])
Z = z.reshape(X.shape)
plt.pcolormesh(X,Y,Z)
plt.show()
。
如果您没有这种能力,并且获得固定z
。您可以执行以下操作。首先,我定义了一个生成虚假数据的函数:
(x,y,z)
这里,返回的矩阵如下所示:
def gen_fake_data():
# First we generate the (x,y,z) tuples to imitate "real" data
# Half of this will be in the + direction, half will be in the - dir.
xy_max_error = 0.2
# Generate the "real" x,y vectors
x = np.linspace(min_x, max_x, dim_x)
y = np.linspace(min_y, max_y, dim_y)
# Apply an error to x,y
x_err = (np.random.rand(*x.shape) - 0.5) * xy_max_error
y_err = (np.random.rand(*y.shape) - 0.5) * xy_max_error
x *= (1 + x_err)
y *= (1 + y_err)
# Generate fake z
rows = []
for ix in x:
for iy in y:
z = math.sqrt(ix**2 + iy**2)
rows.append([ix,iy,z])
mat = np.array(rows)
return mat
方法2:在常规网格上插入给定的mat = [[x_0, y_0, z_0],
[x_1, y_1, z_1],
[x_2, y_2, z_2],
...
[x_n, y_n, z_n]]
点
z
此方法生成以下图表:
方法3:无插值(对采样数据的约束)
还有第三种选择,具体取决于# Method 2:
# This works if you have (x,y,z) tuples that you're *not* generating, and (x,y) points
# may not fall evenly on a grid.
def method_2():
mat = gen_fake_data()
x = np.linspace(min_x, max_x, dim_x)
y = np.linspace(min_y, max_y, dim_y)
X,Y = np.meshgrid(x, y)
# Interpolate (x,y,z) points [mat] over a normal (x,y) grid [X,Y]
# Depending on your "error", you may be able to use other methods
Z = interpolate.griddata((mat[:,0], mat[:,1]), mat[:,2], (X,Y), method='nearest')
plt.pcolormesh(X,Y,Z)
plt.show()
的设置方式。此选项需要两件事: