Python/NumPy中meshgrid的目的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36013063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:17:00  来源:igfitidea点击:

What is the purpose of meshgrid in Python / NumPy?

pythonnumpymultidimensional-arraymeshnumpy-ndarray

提问by HonzaB

Can someone explain to me what is the purpose of meshgridfunction in Numpy? I know it creates some kind of grid of coordinates for plotting, but I can't really see the direct benefit of it.

有人可以向我解释meshgridNumpy中函数的目的是什么吗?我知道它为绘图创建了某种坐标网格,但我无法真正看到它的直接好处。

I am studying "Python Machine Learning" from Sebastian Raschka, and he is using it for plotting the decision borders. See input 11 here.

我正在学习 Sebastian Raschka 的“Python 机器学习”,他用它来绘制决策边界。请参阅此处的输入 11 。

I have also tried this code from official documentation, but, again, the output doesn't really make sense to me.

我也试过官方文档中的这段代码,但同样,输出对我来说没有意义。

x = np.arange(-5, 5, 1)
y = np.arange(-5, 5, 1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)

Please, if possible, also show me a lot of real-world examples.

如果可能的话,也请给我展示很多真实世界的例子。

回答by Suever

The purpose of meshgridis to create a rectangular grid out of an array of x values and an array of y values.

的目的meshgrid是从 x 值数组和 y 值数组中创建一个矩形网格。

So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a rectangular grid, we need every combination of the xand ypoints.

因此,例如,如果我们要创建一个网格,其中在 x 和 y 方向上 0 到 4 之间的每个整数值处都有一个点。要创建矩形网格,我们需要xy点的每个组合。

This is going to be 25 points, right? So if we wanted to create an x and y array for all of these points, we coulddo the following.

这将是 25 分,对吧?因此,如果我们想为所有这些点创建一个 x 和 y 数组,我们可以执行以下操作。

x[0,0] = 0    y[0,0] = 0
x[0,1] = 1    y[0,1] = 0
x[0,2] = 2    y[0,2] = 0
x[0,3] = 3    y[0,3] = 0
x[0,4] = 4    y[0,4] = 0
x[1,0] = 0    y[1,0] = 1
x[1,1] = 1    y[1,1] = 1
...
x[4,3] = 3    y[4,3] = 4
x[4,4] = 4    y[4,4] = 4

This would result in the following xand ymatrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.

这将导致以下矩阵xy矩阵,使得每个矩阵中相应元素的配对给出网格中一个点的 x 和 y 坐标。

x =   0 1 2 3 4        y =   0 0 0 0 0
      0 1 2 3 4              1 1 1 1 1
      0 1 2 3 4              2 2 2 2 2
      0 1 2 3 4              3 3 3 3 3
      0 1 2 3 4              4 4 4 4 4

We can then plot these to verify that they are a grid:

然后我们可以绘制这些以验证它们是一个网格:

plt.plot(x,y, marker='.', color='k', linestyle='none')

enter image description here

在此处输入图片说明

Obviously, this gets very tedious especially for large ranges of xand y. Instead, meshgridcan actually generate this for us: all we have to specify are the unique xand yvalues.

显然,这会变得非常乏味,尤其是对于大范围的xy。相反,meshgrid实际上可以为我们生成这个:我们必须指定的只是唯一值xy值。

xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);

Now, when we call meshgrid, we get the previous output automatically.

现在,当我们调用 时meshgrid,我们会自动获得先前的输出。

xx, yy = np.meshgrid(xvalues, yvalues)

plt.plot(xx, yy, marker='.', color='k', linestyle='none')

enter image description here

在此处输入图片说明

Creation of these rectangular grids is useful for a number of tasks. In the example that you have provided in your post, it is simply a way to sample a function (sin(x**2 + y**2) / (x**2 + y**2)) over a range of values for xand y.

这些矩形网格的创建对于许多任务很有用。在您在您的文章所提供的例子,它是简单地品尝函数(的方式sin(x**2 + y**2) / (x**2 + y**2))在范围值的xy

Because this function has been sampled on a rectangular grid, the function can now be visualized as an "image".

由于此函数已在矩形网格上采样,因此现在可以将该函数可视化为“图像”。

enter image description here

在此处输入图片说明

Additionally, the result can now be passed to functions which expect data on rectangular grid (i.e. contourf)

此外,现在可以将结果传递给期望矩形网格上的数据的函数(即contourf

回答by Hai Phan

Courtesy of Microsoft Excel: 

由 Microsoft Excel 提供: 

enter image description here

在此处输入图片说明

回答by MSeifert

Actually the purpose of np.meshgridis already mentioned in the documentation:

实际上np.meshgrid,文档中已经提到了 的目的:

np.meshgrid

Return coordinate matrices from coordinate vectors.

Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn.

np.meshgrid

从坐标向量返回坐标矩阵。

为 ND 网格上的 ND 标量/矢量场的矢量化评估制作 ND 坐标数组,给定一维坐标数组 x1、x2、...、xn。

So it's primary purpose is to create a coordinates matrices.

所以它的主要目的是创建一个坐标矩阵。

You probably just asked yourself:

你可能只是问过自己:

Why do we need to create coordinate matrices?

为什么我们需要创建坐标矩阵?

The reason you need coordinate matrices with Python/NumPy is that there is no direct relation from coordinates to values, except when your coordinates start with zero and are purely positive integers. Then you can just use the indices of an array as the index. However when that's not the case you somehow need to store coordinates alongside your data. That's where grids come in.

您需要 Python/NumPy 坐标矩阵的原因是,从坐标到值没有直接关系,除非您的坐标从零开始并且是纯正整数。然后你可以只使用数组的索引作为索引。但是,当情况并非如此时,您需要以某种方式将坐标与数据一起存储。这就是网格的用武之地。

Suppose your data is:

假设您的数据是:

1  2  1
2  5  2
1  2  1

However, each value represents a 2 kilometers wide region horizontally and 3 kilometers vertically. Suppose your origin is the upper left corner and you want arrays that represent the distance you could use:

但是,每个值代表水平 2 公里宽和垂直 3 公里宽的区域。假设您的原点是左上角,并且您想要代表您可以使用的距离的数组:

import numpy as np
h, v = np.meshgrid(np.arange(3)*3, np.arange(3)*2)

where v is:

其中 v 是:

array([[0, 0, 0],
       [2, 2, 2],
       [4, 4, 4]])

and h:

和 h:

array([[0, 3, 6],
       [0, 3, 6],
       [0, 3, 6]])

So if you have two indices, let's say xand y(that's why the return value of meshgridis usually xxor xsinstead of xin this case I chose hfor horizontally!) then you can get the x coordinate of the point, the y coordinate of the point and the value at that point by using:

所以,如果你有两个指标,比方说xy(这就是为什么的返回值meshgrid通常是xxxs,而不是x在这种情况下,我选择h了水平!),那么你可以得到该点的x坐标,在Y点和坐标在那个点使用值:

h[x, y]    # horizontal coordinate
v[x, y]    # vertical coordinate
data[x, y]  # value

That makes it much easier to keep track of coordinates and(even more importantly) you can pass them to functions that need to know the coordinates.

这使得跟踪坐标变得更加容易,并且(更重要的是)您可以将它们传递给需要知道坐标的函数。

A slightly longer explanation

稍微长一点的解释

However, np.meshgriditself isn't often used directly, mostly one just uses one of similarobjects np.mgridor np.ogrid. Here np.mgridrepresents the sparse=Falseand np.ogridthe sparse=Truecase (I refer to the sparseargument of np.meshgrid). Note that there is a significant difference between np.meshgridand np.ogridand np.mgrid: The first two returned values (if there are two or more) are reversed. Often this doesn't matter but you should give meaningful variable names depending on the context.

但是,np.meshgrid它本身并不经常直接使用,大多数情况下只是使用类似的对象之一np.mgridnp.ogrid. 这里np.mgrid代表sparse=Falsenp.ogridsparse=True情况下(我指的是sparse的说法np.meshgrid)。注意np.meshgridand 和np.ogridand之间有一个显着的区别 np.mgrid:前两个返回值(如果有两个或更多)是颠倒的。通常这并不重要,但您应该根据上下文给出有意义的变量名称。

For example, in case of a 2D grid and matplotlib.pyplot.imshowit makes sense to name the first returned item of np.meshgridxand the second one ywhile it's the other way around for np.mgridand np.ogrid.

例如,在 2D 网格的情况下,matplotlib.pyplot.imshow将第一个返回的项目命名为 ofnp.meshgridx和第二个是有意义的,y而反过来则为np.mgridand np.ogrid

np.ogridand sparse grids

np.ogrid和稀疏网格

>>> import numpy as np
>>> yy, xx = np.ogrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5],
       [-4],
       [-3],
       [-2],
       [-1],
       [ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5]])

As already said the output is reversed when compared to np.meshgrid, that's why I unpacked it as yy, xxinstead of xx, yy:

正如已经说过的,与 相比np.meshgrid,输出是相反的,这就是为什么我将其解压缩为yy, xx而不是xx, yy

>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6), sparse=True)
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5],
       [-4],
       [-3],
       [-2],
       [-1],
       [ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5]])

This already looks like coordinates, specifically the x and y lines for 2D plots.

这已经看起来像坐标,特别是 2D 绘图的 x 和 y 线。

Visualized:

可视化:

yy, xx = np.ogrid[-5:6, -5:6]
plt.figure()
plt.title('ogrid (sparse meshgrid)')
plt.grid()
plt.xticks(xx.ravel())
plt.yticks(yy.ravel())
plt.scatter(xx, np.zeros_like(xx), color="blue", marker="*")
plt.scatter(np.zeros_like(yy), yy, color="red", marker="x")

enter image description here

在此处输入图片说明

np.mgridand dense/fleshed out grids

np.mgrid和密集/充实的网格

>>> yy, xx = np.mgrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
       [-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
       [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
       [-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
       [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5]])

The same applies here: The output is reversed compared to np.meshgrid:

这同样适用于:与 相比,输出相反np.meshgrid

>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6))
>>> xx
array([[-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5],
       [-5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
       [-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
       [-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
       [-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
       [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1],
       [ 2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2],
       [ 3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3],
       [ 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4],
       [ 5,  5,  5,  5,  5,  5,  5,  5,  5,  5,  5]])

Unlike ogridthese arrays contain allxxand yycoordinates in the -5 <= xx <= 5; -5 <= yy <= 5 grid.

不像ogrid这些数组包含所有xxyy坐标在 -5 <= xx <= 5; -5 <= yy <= 5 网格。

yy, xx = np.mgrid[-5:6, -5:6]
plt.figure()
plt.title('mgrid (dense meshgrid)')
plt.grid()
plt.xticks(xx[0])
plt.yticks(yy[:, 0])
plt.scatter(xx, yy, color="red", marker="x")

enter image description here

在此处输入图片说明

Functionality

功能

It's not only limited to 2D, these functions work for arbitrary dimensions (well, there is a maximum number of arguments given to function in Python and a maximum number of dimensions that NumPy allows):

它不仅限于 2D,这些函数适用于任意维度(好吧,Python 中为函数提供了最大数量的参数,而 NumPy 允许的最大维度数量):

>>> x1, x2, x3, x4 = np.ogrid[:3, 1:4, 2:5, 3:6]
>>> for i, x in enumerate([x1, x2, x3, x4]):
...     print('x{}'.format(i+1))
...     print(repr(x))
x1
array([[[[0]]],


       [[[1]]],


       [[[2]]]])
x2
array([[[[1]],

        [[2]],

        [[3]]]])
x3
array([[[[2],
         [3],
         [4]]]])
x4
array([[[[3, 4, 5]]]])

>>> # equivalent meshgrid output, note how the first two arguments are reversed and the unpacking
>>> x2, x1, x3, x4 = np.meshgrid(np.arange(1,4), np.arange(3), np.arange(2, 5), np.arange(3, 6), sparse=True)
>>> for i, x in enumerate([x1, x2, x3, x4]):
...     print('x{}'.format(i+1))
...     print(repr(x))
# Identical output so it's omitted here.

Even if these also work for 1D there are two (much more common) 1D grid creation functions:

即使这些也适用于一维,也有两个(更常见的)一维网格创建函数:

Besides the startand stopargument it also supports the stepargument (even complex steps that represent the number of steps):

除了startandstop参数之外,它还支持step参数(甚至表示步骤数的复杂步骤):

>>> x1, x2 = np.mgrid[1:10:2, 1:10:4j]
>>> x1  # The dimension with the explicit step width of 2
array([[1., 1., 1., 1.],
       [3., 3., 3., 3.],
       [5., 5., 5., 5.],
       [7., 7., 7., 7.],
       [9., 9., 9., 9.]])
>>> x2  # The dimension with the "number of steps"
array([[ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.],
       [ 1.,  4.,  7., 10.]])

Applications

应用

You specifically asked about the purpose and in fact, these grids are extremely useful if you need a coordinate system.

您特别询问了目的,事实上,如果您需要坐标系,这些网格非常有用。

For example if you have a NumPy function that calculates the distance in two dimensions:

例如,如果您有一个计算二维距离的 NumPy 函数:

def distance_2d(x_point, y_point, x, y):
    return np.hypot(x-x_point, y-y_point)

And you want to know the distance of each point:

而你想知道每个点的距离:

>>> ys, xs = np.ogrid[-5:5, -5:5]
>>> distances = distance_2d(1, 2, xs, ys)  # distance to point (1, 2)
>>> distances
array([[9.21954446, 8.60232527, 8.06225775, 7.61577311, 7.28010989,
        7.07106781, 7.        , 7.07106781, 7.28010989, 7.61577311],
       [8.48528137, 7.81024968, 7.21110255, 6.70820393, 6.32455532,
        6.08276253, 6.        , 6.08276253, 6.32455532, 6.70820393],
       [7.81024968, 7.07106781, 6.40312424, 5.83095189, 5.38516481,
        5.09901951, 5.        , 5.09901951, 5.38516481, 5.83095189],
       [7.21110255, 6.40312424, 5.65685425, 5.        , 4.47213595,
        4.12310563, 4.        , 4.12310563, 4.47213595, 5.        ],
       [6.70820393, 5.83095189, 5.        , 4.24264069, 3.60555128,
        3.16227766, 3.        , 3.16227766, 3.60555128, 4.24264069],
       [6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
        2.23606798, 2.        , 2.23606798, 2.82842712, 3.60555128],
       [6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
        1.41421356, 1.        , 1.41421356, 2.23606798, 3.16227766],
       [6.        , 5.        , 4.        , 3.        , 2.        ,
        1.        , 0.        , 1.        , 2.        , 3.        ],
       [6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
        1.41421356, 1.        , 1.41421356, 2.23606798, 3.16227766],
       [6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
        2.23606798, 2.        , 2.23606798, 2.82842712, 3.60555128]])

The output would be identical if one passed in a dense grid instead of an open grid. NumPys broadcasting makes it possible!

如果通过密集网格而不是开放网格,输出将是相同的。NumPys 广播使之成为可能!

Let's visualize the result:

让我们可视化结果:

plt.figure()
plt.title('distance to point (1, 2)')
plt.imshow(distances, origin='lower', interpolation="none")
plt.xticks(np.arange(xs.shape[1]), xs.ravel())  # need to set the ticks manually
plt.yticks(np.arange(ys.shape[0]), ys.ravel())
plt.colorbar()

enter image description here

在此处输入图片说明

And this is also when NumPys mgridand ogridbecome very convenient because it allows you to easily change the resolution of your grids:

这也是当NumPysmgridogrid变得非常方便,因为它可以让你轻松更改网格的分辨率:

ys, xs = np.ogrid[-5:5:200j, -5:5:200j]
# otherwise same code as above

enter image description here

在此处输入图片说明

However, since imshowdoesn't support xand yinputs one has to change the ticks by hand. It would be really convenient if it would accept the xand ycoordinates, right?

但是,由于imshow不支持xy输入,因此必须手动更改刻度。如果它接受xy坐标,那真的很方便,对吧?

It's easy to write functions with NumPy that deal naturally with grids. Furthermore, there are several functions in NumPy, SciPy, matplotlib that expect you to pass in the grid.

使用 NumPy 编写自然处理网格的函数很容易。此外,NumPy、SciPy、matplotlib 中有几个函数希望您传入网格。

I like images so let's explore matplotlib.pyplot.contour:

我喜欢图像所以让我们探索matplotlib.pyplot.contour

ys, xs = np.mgrid[-5:5:200j, -5:5:200j]
density = np.sin(ys)-np.cos(xs)
plt.figure()
plt.contour(xs, ys, density)

enter image description here

在此处输入图片说明

Note how the coordinates are already correctly set! That wouldn't be the case if you just passed in the density.

注意坐标是如何正确设置的!如果您只是通过density.

Or to give another fun example using astropy models(this time I don't care much about the coordinates, I just use them to create somegrid):

或者再举一个使用天体模型的有趣例子(这次我不太关心坐标,我只是用它们来创建一些网格):

from astropy.modeling import models
z = np.zeros((100, 100))
y, x = np.mgrid[0:100, 0:100]
for _ in range(10):
    g2d = models.Gaussian2D(amplitude=100, 
                           x_mean=np.random.randint(0, 100), 
                           y_mean=np.random.randint(0, 100), 
                           x_stddev=3, 
                           y_stddev=3)
    z += g2d(x, y)
    a2d = models.AiryDisk2D(amplitude=70, 
                            x_0=np.random.randint(0, 100), 
                            y_0=np.random.randint(0, 100), 
                            radius=5)
    z += a2d(x, y)

enter image description here

在此处输入图片说明

Although that's just "for the looks" several functions related to functional models and fitting (for example scipy.interpolate.interp2d, scipy.interpolate.griddataeven show examples using np.mgrid) in Scipy, etc. require grids. Most of these work with open grids and dense grids, however some only work with one of them.

尽管这只是“外观”,但与Scipy 等中的功能模型和拟合(例如scipy.interpolate.interp2dscipy.interpolate.griddata甚至使用 显示示例np.mgrid)相关的一些功能需要网格。其中大多数适用于开放网格和密集网格,但有些仅适用于其中之一。

回答by MSeifert

Suppose you have a function:

假设你有一个函数:

def sinus2d(x, y):
    return np.sin(x) + np.sin(y)

and you want, for example, to see what it looks like in the range 0 to 2*pi. How would you do it? There np.meshgridcomes in:

例如,您想查看它在 0 到 2*pi 范围内的样子。你会怎么做?有np.meshgrid来自于:

xx, yy = np.meshgrid(np.linspace(0,2*np.pi,100), np.linspace(0,2*np.pi,100))
z = sinus2d(xx, yy) # Create the image on this grid

and such a plot would look like:

这样的情节看起来像:

import matplotlib.pyplot as plt
plt.imshow(z, origin='lower', interpolation='none')
plt.show()

enter image description here

在此处输入图片说明

So np.meshgridis just a convenience. In principle the same could be done by:

所以np.meshgrid只是一种方便。原则上,可以通过以下方式完成相同的操作:

z2 = sinus2d(np.linspace(0,2*np.pi,100)[:,None], np.linspace(0,2*np.pi,100)[None,:])

but there you need to be aware of your dimensions (suppose you have more than two ...) and the right broadcasting. np.meshgriddoes all of this for you.

但在那里你需要了解你的维度(假设你有两个以上......)和正确的广播。np.meshgrid为你做这一切。

Also meshgrid allows you to delete coordinates together with the data if you, for example, want to do an interpolation but exclude certain values:

如果您想要进行插值但排除某些值,meshgrid 还允许您将坐标与数据一起删除:

condition = z>0.6
z_new = z[condition] # This will make your array 1D

so how would you do the interpolation now? You can give xand yto an interpolation function like scipy.interpolate.interp2dso you need a way to know which coordinates were deleted:

那么你现在将如何进行插值?你可以给xy一个插值函数,scipy.interpolate.interp2d所以你需要一种方法来知道哪些坐标被删除了:

x_new = xx[condition]
y_new = yy[condition]

and then you can still interpolate with the "right" coordinates (try it without the meshgrid and you will have a lot of extra code):

然后您仍然可以使用“正确”坐标进行插值(在没有网格的情况下尝试它,您将有很多额外的代码):

from scipy.interpolate import interp2d
interpolated = interp2(x_new, y_new, z_new)

and the original meshgrid allows you to get the interpolation on the original grid again:

原始网格允许您再次在原始网格上进行插值:

interpolated_grid = interpolated(xx, yy)

These are just some examples where I used the meshgridthere might be a lot more.

这些只是我使用的一些示例,meshgrid可能还有更多示例。

回答by Narasimhan

meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.

meshgrid 有助于从两个阵列的所有点对的两个一维阵列创建矩形网格。

x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])

Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:

现在,如果您已经定义了一个函数 f(x,y) 并且您想将此函数应用于数组 'x' 和 'y' 中所有可能的点组合,那么您可以这样做:

f(*np.meshgrid(x, y))

Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.

比方说,如果你的函数只产生两个元素的乘积,那么这就是如何实现笛卡尔积,有效地用于大型数组。

Referred from here

这里引用

回答by user3780389

Basic Idea

基本理念

Given possible x values, xs, (think of them as the tick-marks on the x-axis of a plot) and possible y values, ys, meshgridgenerates the corresponding set of (x, y) grid points---analogous to set((x, y) for x in xs for y in yx). For example, if xs=[1,2,3]and ys=[4,5,6], we'd get the set of coordinates {(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}.

给定可能的 x 值 , xs(将它们视为绘图 x 轴上的刻度线)和可能的 y 值ysmeshgrid生成相应的 (x, y) 网格点集---类似于set((x, y) for x in xs for y in yx)。例如,如果xs=[1,2,3]ys=[4,5,6],我们将得到坐标集{(1,4), (2,4), (3,4), (1,5), (2,5), (3,5), (1,6), (2,6), (3,6)}

Form of the Return Value

返回值的形式

However, the representation that meshgridreturns is different from the above expression in two ways:

但是,meshgrid返回的表示与上述表达式有两个不同之处:

First, meshgridlays out the grid points in a 2d array: rows correspond to different y-values, columns correspond to different x-values---as in list(list((x, y) for x in xs) for y in ys), which would give the following array:

首先meshgrid在 2d 数组中布置网格点:行对应于不同的 y 值,列对应于不同的 x 值---如list(list((x, y) for x in xs) for y in ys),这将给出以下数组:

   [[(1,4), (2,4), (3,4)],
    [(1,5), (2,5), (3,5)],
    [(1,6), (2,6), (3,6)]]

Second, meshgridreturns the x and y coordinates separately (i.e. in two different numpy 2d arrays):

其次,分别meshgrid返回 x 和 y 坐标(即在两个不同的 numpy 二维数组中):

   xcoords, ycoords = (
       array([[1, 2, 3],
              [1, 2, 3],
              [1, 2, 3]]),
       array([[4, 4, 4],
              [5, 5, 5],
              [6, 6, 6]]))
   # same thing using np.meshgrid:
   xcoords, ycoords = np.meshgrid([1,2,3], [4,5,6])
   # same thing without meshgrid:
   xcoords = np.array([xs] * len(ys)
   ycoords = np.array([ys] * len(xs)).T

Note, np.meshgridcan also generate grids for higher dimensions. Given xs, ys, and zs, you'd get back xcoords, ycoords, zcoords as 3d arrays. meshgridalso supports reverse ordering of the dimensions as well as sparse representation of the result.

注意,np.meshgrid也可以为更高维度生成网格。给定 xs、ys 和 zs,您将返回 xcoords、ycoords、zcoords 作为 3d 数组。meshgrid还支持维度的反向排序以及结果的稀疏表示。

Applications

应用

Why would we want this form of output?

为什么我们需要这种形式的输出?

Apply a function at every point on a grid:One motivation is that binary operators like (+, -, *, /, **) are overloaded for numpy arrays as elementwise operations. This means that if I have a function def f(x, y): return (x - y) ** 2that works on two scalars, I can also apply it on two numpy arrays to get an array of elementwise results: e.g. f(xcoords, ycoords)or f(*np.meshgrid(xs, ys))gives the following on the above example:

在网格上的每个点应用一个函数:一个动机是像 (+, -, *, /, **) 这样的二元运算符被重载为 numpy 数组作为元素操作。这意味着如果我有一个def f(x, y): return (x - y) ** 2适用于两个标量的函数,我也可以将它应用于两个 numpy 数组以获取元素结果数组:例如f(xcoords, ycoords)f(*np.meshgrid(xs, ys))在上面的示例中给出以下内容:

array([[ 9,  4,  1],
       [16,  9,  4],
       [25, 16,  9]])

Higher dimensional outer product:I'm not sure how efficient this is, but you can get high-dimensional outer products this way: np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0).

高维外积:我不确定这有多有效,但您可以通过这种方式获得高维外积:np.prod(np.meshgrid([1,2,3], [1,2], [1,2,3,4]), axis=0).

Contour plots in matplotlib:I came across meshgridwhen investigating drawing contour plots with matplotlibfor plotting decision boundaries. For this, you generate a grid with meshgrid, evaluate the function at each grid point (e.g. as shown above), and then pass the xcoords, ycoords, and computed f-values (i.e. zcoords) into the contourf function.

在matplotlib云图:我遇到meshgrid调查时绘制等高线图与matplotlib用于绘制的决策边界。为此,您使用 生成一个网格meshgrid,在每个网格点评估函数(例如,如上所示),然后将 xcoords、ycoords 和计算出的 f 值(即 zcoords)传递给 contourf 函数。