2 views
in Python

Can someone explain to me what is the purpose of meshgrid function 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.

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

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 (106k points)
edited by

Mesh grid suppose you have a function as follows:-

def sinus2d(x, y):

return np.sin(x) + np.sin(y)

And such a plot would look like:

import matplotlib.pyplot as plt

plt.imshow(z, origin='lower', interpolation='none')

plt.show()

by (20.3k points)

If you want to create an x and y array for all of these points, then you can try the following.

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 will result in the following x and y matrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.

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

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

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

But, it'll be difficult for large ranges of x and y. Instead, you can specify the unique x and y values like this:

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

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

Now, when you call meshgrid, you'll get the previous output automatically.

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

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