【问题标题】:matplotlib creating 2D arrays from 1D arrays - is there a nicer way?matplotlib 从一维数组创建二维数组 - 有更好的方法吗?
【发布时间】: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


【解决方案1】:

如果您的数据与您在示例中给出的数据一样,则您已经有了一个网格(每对 (x,y) 的 z 值),您只需要重新调整数组的形状:

cols = np.unique(xs).shape[0]
X = xs.reshape(-1, cols)
Y = ys.reshape(-1, cols)
Z = zs.reshape(-1, cols)

【讨论】:

  • 谢谢。这要简单得多。但是,我还有一个问题/并发症。如果 xs, ys 不是正常顺序怎么办?例如xs = [1,2,4,3,5,5,4,3,1,2....] 然后,如果您执行上述操作并将其传递给 matplotlib 函数,它似乎会尝试连接点,这很奇怪。这里的解决方案只是预先对表格进行排序吗?
  • @user2175850 回答您的问题...您将不得不排序两次。首先将您的数据放入一个二维数组中:a = np.vstack((xs,ys,zs)).T,然后在 x 中排序:a = a[np.argsort(a[:,0])],然后在 y 中:a = a[np.argsort(a[:,1])],然后将排序后的数据返回:xs, ys, zs = a.T
  • 谢谢。连续执行两个 argsort 不起作用,因为一种消除了前一种的影响。我使用 lexsort 解决了这个问题。 a= a[numpy.lexsort((a[:,0],a[:,1]))]。现在一切正常。
猜你喜欢
  • 2016-12-27
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 2021-11-30
相关资源
最近更新 更多