【发布时间】:2014-02-16 14:17:46
【问题描述】:
我正在尝试使用 matplotlibs 等高线图、曲面图和线框图来可视化一些 3d 数据。
我的原始数据是一个 numpy 数组的形式,其中 x、y 和 z 分别在自己的列中(例如):
| xs |是的zs |
|---|---|----|
| 1 | 1 | 3 |
| 2 | 1 | 4 |
| 3 | 1 | 2 |
| 4 | 1 | 3 |
| 5 | 1 | 5 |
| 1 | 2 | -1 |
| 2 | 2 | -1 |
| 3 | 2 | -2 |
| 4 | 2 | 2 |
| 5 | 2 | 7 |
| 1 | 3 | 5 |
| 2 | 3 | 2 |
| 3 | 3 | 3 |
| 4 | 3 | 2 |
| 5 | 3 | 3 |
现在一些绘图函数只获取与我的列 (xs,ys,zs) 对应的一维数组中的数据。但是,有些需要二维数组(网格)格式。有没有一种简单的方法可以将 3 个 1D 数组转换为 3 个 2D 数组的正确格式?我尝试过使用 numpy.meshgrid ,虽然这适用于创建 X 和 Y 2D 数组,但我无法找到创建相应 Z 2D 数组的好方法。我设法通过制作一个空白的二维数组并用适当的 Z 值填充它来做到这一点,但这不是很好。有没有更好的方法来创建 Z 二维数组?
以下是我的尝试(有效)。有没有办法在不循环 X 和 Y 的情况下制作 Z 数组?
def getMeshGrid(dataArray):
"""get 2d coordinate grid and Z values in meshgrid format. requires values in
dataArray to have a rectangular region of x-y space covered uniformly"""
xs = dataArray[:,0]
ys = dataArray[:,1]
xmin,xmax = xs.min(), xs.max()
xstep = xs[xs!=xmin].min()-xmin
ymin,ymax = ys.min(), ys.max()
ystep = ys[ys!=ymin].min()-ymin
X = numpy.arange(xmin, xmax+xstep, xstep)
Y = numpy.arange(ymin, ymax+ystep, ystep)
X,Y = numpy.meshgrid(X,Y)
Z = numpy.zeros(X.shape)
height, width = X.shape
for i in range(0, height):
for j in range(0,width):
halfway = dataArray[dataArray[:,0]==X[i,j]] # finds all with that value of x
row = halfway[halfway[:,1]==Y[i,j]] # finds y value
Z[i,j] = row[0,6]
return X,Y,Z
提前致谢
【问题讨论】:
标签: python arrays numpy matplotlib