meshgrid() (NumPy)
np.meshgrid() takes 1-D coordinate arrays and returns 2-D coordinate matrices covering every combination, so you can evaluate functions or plot surfaces over a 2-D grid of points.
NumPy
Given x and y axis values, meshgrid returns two arrays X and Y where each cell holds the x or y coordinate of a point on the grid. Pairing them up gives every (x, y) combination, which is exactly what you need to compute z = f(x, y) over a plane in one vectorized expression.
It is the foundation of surface plots, contour plots, and heatmaps: you build the grid with meshgrid, evaluate your function on X and Y, and pass the result to a plotting routine. The 'ij' versus 'xy' indexing argument controls whether the first axis is rows or columns.
For large grids, meshgrid materializes full coordinate arrays; np.mgrid and sparse meshgrids (sparse=True) are memory-lighter alternatives when broadcasting can do the rest.
Syntax
X, Y = np.meshgrid(x, y, indexing='xy')Examples
Python
import numpy as np
X, Y = np.meshgrid([1, 2, 3], [10, 20])
print(X)
print(Y)Output:
[[1 2 3]
[1 2 3]]
[[10 10 10]
[20 20 20]]Learn it in a lesson
- meshgrid →