NumPy np.meshgrid tutorial - Programming Languages - Python

NumPy np.meshgrid Tutorial for Beginners

Matrix operations are a useful tool for data analysts when modifying structured data. For example, if you already have a table of prices for a set of products by region and need to convert all prices to a single currency, matrix multiplication will likely be the fastest way to get the prices adjusted.

NumPy, Python’s prominent scientific computing package, offers a convenient way to implement matrix operations through the np.meshgrid method. In this article, you’ll learn how to use meshgrid, and why you might want to create grids from NumPy arrays. You’ll also visualize data using meshgrid, and explore practical applications of matrix math.

What Is NumPy Meshgrid?

Meshgrid is a method from Python’s NumPy library, which Python programmers frequently use for scientific computing. Meshgrid is a combination of the words ”mesh” and “grid,” which both refer to a network-like structure. Building such structures is the meshgrid method’s primary purpose.

NumPy arrays are the preferred data structure for large volumes of data in NumPy because of their performance and memory-efficiency. Meshgrid turns one-dimensional NumPy arrays into grids called matrices. If we pass two NumPy arrays into meshgrid, we get two matrices back. Below we use meshgrid to create two grids from two arrays: 

import numpy as np
array_a = [1,2,3,4]
array_b = [10,20,30,40]

XX,YY = np.meshgrid(array_a, array_b)

XX
>>> array([
      [1, 2, 3, 4, 5],
      [1, 2, 3, 4, 5],
      [1, 2, 3, 4, 5],
      [1, 2, 3, 4, 5],
      [1, 2, 3, 4, 5]])

YY
>>> array([
      [10, 10, 10, 10, 10],
      [20, 20, 20, 20, 20],
      [30, 30, 30, 30, 30],
      [40, 40, 40, 40, 40],
      [50, 50, 50, 50, 50]])

The grids, or matrices, that meshgrid generates are suitable for matrix math and plotting, among other things. In the following sections, we’ll talk more about matrices and what makes meshgrid useful.

What Are Matrices in Python?

A matrix is a two-dimensional grid-like arrangement of numbers. The numbers in a matrix are organized by rows and columns. Matrices allow for mathematical operations such as addition, multiplication, and raising elements to a power. Using matrices allows us to perform linear algebra, with which we can efficiently perform many computations on many numbers. In our previous example, XX and YY were matrices.

Let’s go over the code anew:

import numpy as np

array_a = [1,2,3,4]
array_b = [10,20,30,40]

XX,YY = np.meshgrid(array_a, array_b)

XX
>>> array([
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])

YY
>>> array([
       [10, 10, 10, 10, 10],
       [20, 20, 20, 20, 20],
       [30, 30, 30, 30, 30],
       [40, 40, 40, 40, 40],
       [50, 50, 50, 50, 50]])

Meshgrid takes two arrays of different lengths and manipulates them. In the first matrix, every column has a different number. In the second matrix, every row has a different number. Placing these two matrices on top of one another gives us every possible combination between the values of array_a and the values of array_b

For instance, the first value in array_a, which is the number 1, can be combined in following ways with the values of array_b: (1,10), (1,20), (1,30), (1,40) and (1,50). We can access these values by indexing both matrices with the same indices:

  • Horizontal coordinate XX[0,0] stores 1.
  • Vertical coordinate YY[0,0] stores 10.
  • The final value of the coordinates is (1,10). 

You can access other values similarly: [1,0] for (1,20), [2,0] for (1,30), and so on. This way, all possible combinations of numbers are enumerated and may be traversed by changing the number of rows and columns.

XX and YY matrices are also called coordinate matrices. These matrices are useful because they allow us to map values to positions in a coordinate system. This makes it easy to keep track of which values are stored at which coordinates. More importantly, coordinate matrices allow us to apply functions to them and transform the coordinate system. This is interesting because it allows us to visualize properties of data and how applying different mathematical functions to the data changes it.

Meshgrid Uses

Meshgrid turns NumPy arrays into coordinate matrices, or grids of values. Using the matplotlib library, a widely used Python library for creating plots and charts, we can visually represent the two matrices from our example above. The resulting plot contains a grid of values:

import matplotlib.pyplot as plt

plt.plot(XX, YY, marker=".", color='k', linestyle='none')

plt.xticks(array_a)
plt.yticks(array_b)

plt.show()

We can refer to each value in the matrix we defined through the value’s position on the X and Y axes. Alternatively, we can use other NumPy methods to perform various mathematical operations and transform the matrix. Additionally, we could run a mathematical function over the elements in the matrix and visualize their updated values.

If you’ve ever dabbled in machine learning, you’ve probably seen meshgrid in action. Meshgrid is often used to visualize the loss function of a machine learning model and how the margin for error of the results the model predicts decreases as the model learns and updates its parameters.

Now that we’ve worked through mapping a single matrix, let’s see how we can use meshgrid to plot a function.

Plotting Two-Dimensional Functions

To plot a function we’ll need some additional code compared to the plotting we did with a static matrix in the previous section. First, we’ll define a sine function:

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

We’ll apply our function over the two arrays that we defined previously and store the result into a variable Z:

XX, YY = np.meshgrid(array_a, array_b)
Z = sin(XX, YY) 

We’ll then plot the results:

fig = plt.figure(figsize=(9, 6))
# Build the plot
plt.imshow(Z, origin="lower")

# Display a color scale (values denoted by colors)
plt.colorbar()

# Limit the number of values on the axes to 4
plt.locator_params(axis='y', nbins=4)
plt.locator_params(axis='x', nbins=4)
# Display the plot
plt.show()

Unfortunately, the resulting visualization does not contain enough detail for us to understand the behavior of our sine function, since our 4×4 grid was too small to visualize the function’s entire range of values. Let’s give it another attempt on a larger grid. We’ll use NumPy’s linspace method to create two grids consisting of 100 linearly spaced values between –10 and 10.

XX, YY = np.meshgrid(np.linspace(-10,10,100), np.linspace(-10,10,100))
Z = sin(XX, YY) 

The new plot looks like this:

The new grid looks more detailed. Sampling the function on a larger grid allowed us to visualize the sine function’s characteristic periodicity. Increasing the number of values would make the visualization even smoother, whereas decreasing it would make it more coarse.

You can plot any function as long as you can apply it to the coordinates of the elements in a matrix. Here’s another example of a two-dimensional function:

Z = XX ** 2 + (YY - XX) * 2

We can likewise use meshgrid to visualize three-dimensional functions. Let’s see how.

Plotting Three-Dimensional Functions

To plot a three-dimensional function, we’ll need an additional import:

from mpl_toolkits.mplot3d import Axes3D

We’ll create our matrices:

XX, YY = np.meshgrid(np.linspace(-30,30,15), np.linspace(-30,30,15))

Z = XX ** 2 + (YY - XX) * 2

Next, we’ll visualize them:

fig = plt.figure(figsize=(10, 14))
ax = fig.gca(projection="3d")
ax.plot_surface(XX,YY,Z)
plt.show()

Voila! We’ve created a three-dimensional surface plot of a function.

Start Coding Today

In this article, we covered NumPy’s meshgrid and showed how to use it to visualize data and perform various matrix transformations. We also covered matplotlib, a popular Python library used for data visualization, and showed examples of plotting functions with matplotlib and meshgrid. 

Interested in learning how to code? 

Check out our top-rated Introduction to Programming Nanodegree program! You’ll learn the fundamentals of Python and take that first step towards a career in software development, machine learning, or data science.