Show Sidebar Hide Sidebar

Meshgrid

A Meshgrid is an ND-coordinate space generated by a set of arrays. Each point on the meshgrid corresponds to a combination of one value from each of the arrays.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Imports

This tutorial imports Plotly and Numpy.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np

Linspace/Arange to Meshgrid

The np.meshgrid() function can be used to produce N-D coordinate grids. Let's construct an example to fully understand this.

If you give np.meshgrid() two 1D arrays Array $A$ and Array $B$ such that $A$ is

$$ \begin{align*} [a_1, a_2, a_3] \end{align*} $$

and $B$ is

$$ \begin{align*} [b_1, b_2, b_3] \end{align*} $$

then running np.meshgrid(A, B) returns a list of two 2D arrays, which look like

$$ \begin{align*} [[a_1, a_1, a_1], [a_2, a_2, a_2], [a_3, a_3, a_3]] \end{align*} $$

and

$$ \begin{align*} [[b_1, b_1, b_1], [b_2, b_2, b_2], [b_3, b_3, b_3]] \end{align*} $$

for which each array here contains arrays with an array full of the first item, the next filled with all the next item in the original array, etc.

By adding these two arrays together, we can create the 2D array containing, as its elements, every combination of sums between the numbers in the original elements. Arrays such as linspace and arange are typically used to constuct N-D arrays used to plot in 3 dimensions.

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go

x = np.arange(-10, 10, 0.4)
y = np.arange(-10, 10, 0.4)
XX, YY = np.meshgrid(x, y)
ZZ = np.sin(XX**2 + YY**2) / (XX**2 + YY**2)

lines = []
line_marker = dict(color='#0066FF', width=2)
for i, j, k in zip(XX, YY, ZZ):
    lines.append(go.Scatter3d(x=i, y=j, z=k, mode='lines', line=line_marker))

layout = go.Layout(
    title='Wireframe with Meshgrid',
    showlegend=False
)

fig = go.Figure(data=lines, layout=layout)
py.iplot(fig, filename='numpy-arange-to-meshgrid')
Out[2]:
In [3]:
help(np.meshgrid)
Help on function meshgrid in module numpy.lib.function_base:

meshgrid(*xi, **kwargs)
    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.
    
    .. versionchanged:: 1.9
       1-D and 0-D cases are allowed.
    
    Parameters
    ----------
    x1, x2,..., xn : array_like
        1-D arrays representing the coordinates of a grid.
    indexing : {'xy', 'ij'}, optional
        Cartesian ('xy', default) or matrix ('ij') indexing of output.
        See Notes for more details.
    
        .. versionadded:: 1.7.0
    sparse : bool, optional
        If True a sparse grid is returned in order to conserve memory.
        Default is False.
    
        .. versionadded:: 1.7.0
    copy : bool, optional
        If False, a view into the original arrays are returned in order to
        conserve memory.  Default is True.  Please note that
        ``sparse=False, copy=False`` will likely return non-contiguous
        arrays.  Furthermore, more than one element of a broadcast array
        may refer to a single memory location.  If you need to write to the
        arrays, make copies first.
    
        .. versionadded:: 1.7.0
    
    Returns
    -------
    X1, X2,..., XN : ndarray
        For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
        return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
        or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
        with the elements of `xi` repeated to fill the matrix along
        the first dimension for `x1`, the second for `x2` and so on.
    
    Notes
    -----
    This function supports both indexing conventions through the indexing
    keyword argument.  Giving the string 'ij' returns a meshgrid with
    matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
    In the 2-D case with inputs of length M and N, the outputs are of shape
    (N, M) for 'xy' indexing and (M, N) for 'ij' indexing.  In the 3-D case
    with inputs of length M, N and P, outputs are of shape (N, M, P) for
    'xy' indexing and (M, N, P) for 'ij' indexing.  The difference is
    illustrated by the following code snippet::
    
        xv, yv = meshgrid(x, y, sparse=False, indexing='ij')
        for i in range(nx):
            for j in range(ny):
                # treat xv[i,j], yv[i,j]
    
        xv, yv = meshgrid(x, y, sparse=False, indexing='xy')
        for i in range(nx):
            for j in range(ny):
                # treat xv[j,i], yv[j,i]
    
    In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
    
    See Also
    --------
    index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
                     using indexing notation.
    index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
                     using indexing notation.
    
    Examples
    --------
    >>> nx, ny = (3, 2)
    >>> x = np.linspace(0, 1, nx)
    >>> y = np.linspace(0, 1, ny)
    >>> xv, yv = meshgrid(x, y)
    >>> xv
    array([[ 0. ,  0.5,  1. ],
           [ 0. ,  0.5,  1. ]])
    >>> yv
    array([[ 0.,  0.,  0.],
           [ 1.,  1.,  1.]])
    >>> xv, yv = meshgrid(x, y, sparse=True)  # make sparse output arrays
    >>> xv
    array([[ 0. ,  0.5,  1. ]])
    >>> yv
    array([[ 0.],
           [ 1.]])
    
    `meshgrid` is very useful to evaluate functions on a grid.
    
    >>> x = np.arange(-5, 5, 0.1)
    >>> y = np.arange(-5, 5, 0.1)
    >>> xx, yy = meshgrid(x, y, sparse=True)
    >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
    >>> h = plt.contourf(x,y,z)

Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.