How to Plot a 2D NumPy Array in Python Using Matplotlib

Have you ever looked at a massive 2D NumPy array full of numbers and felt like you were staring into the Matrix? I’ve been there many times during my ten years as a Python developer.

Data is often messy, especially when you are dealing with large grids of information like regional temperatures or population densities.

While looking at raw numbers in a Python console is fine for small tasks, it is impossible to spot trends without a visual. That is where the Python Matplotlib library becomes your best friend.

In this tutorial, I will show you exactly how I visualize 2D NumPy arrays using Matplotlib functions. I’ll use real-world scenarios to make it easy to follow.

Method 1: Use imshow() to Visualize Heatmaps in Python

The imshow() function is my “go-to” tool when I need to create a heatmap. It treats each element in your 2D array as a pixel.

Imagine we are tracking the average temperature variations across a grid representing a section of the Midwest. I use this method because it is incredibly fast and efficient.

Below is the Python code I use to generate a synthetic heat map of temperatures.

import matplotlib.pyplot as plt
import numpy as np

# Setting a seed for reproducibility
np.random.seed(42)

# I am creating a 10x10 grid representing a 100-mile square area
# Each value represents temperature in Fahrenheit
temperature_data = np.random.uniform(low=60, high=95, size=(10, 10))

# Creating the plot
plt.figure(figsize=(8, 6))
plt.imshow(temperature_data, cmap='hot', interpolation='nearest')

# Adding a colorbar to understand the temperature scale
plt.colorbar(label='Temperature (°F)')

# Labeling the plot for a professional look
plt.title('Midwest Regional Temperature Heatmap (2D Array)')
plt.xlabel('West-to-East Grid')
plt.ylabel('North-to-South Grid')

# Displaying the final result
plt.show()

I executed the above example code and added the screenshot below.

Plot a 2D NumPy Array in Python Using Matplotlib

When you run this, Matplotlib maps the values to colors. Higher temperatures appear “hotter” (brighter), and lower values appear darker.

I find that using interpolation=’nearest’ is best when you want to see the distinct boundaries of each data point in your Python array.

Method 2: Use pcolormesh() for Non-Uniform Grids

Sometimes, my data isn’t perfectly square. In those cases, I prefer using pcolormesh().

While imshow() is great for images, pcolormesh() is much more robust for mathematical plotting and larger datasets.

Suppose we are looking at housing price density in a suburban area of California. The grid might be irregular, and pcolormesh() handles these coordinates beautifully.

import matplotlib.pyplot as plt
import numpy as np

# Generating a coordinate system (X and Y axis)
# Think of these as longitude and latitude coordinates in a US city
x = np.linspace(0, 50, 20)
y = np.linspace(0, 50, 20)
X, Y = np.meshgrid(x, y)

# Creating a 2D array based on a mathematical function
# This simulates a "peak" in housing prices in a city center
Z = np.exp(-((X-25)**2 + (Y-25)**2) / 200) * 1000

# Plotting using pcolormesh
plt.figure(figsize=(8, 6))
plt.pcolormesh(X, Y, Z, shading='auto', cmap='viridis')

# Adding labels for clarity
plt.colorbar(label='Avg House Price (in $1000s)')
plt.title('Housing Density Distribution in California Suburbs')
plt.xlabel('Distance East (Miles)')
plt.ylabel('Distance North (Miles)')

plt.show()

I executed the above example code and added the screenshot below.

Plot 2D NumPy Array Using Matplotlib

I personally use shading=’auto’ because it ensures the colors align correctly with the grid lines. This method is standard in Python scientific computing.

Method 3: Create Contour Plots for Topographic Data

If you have ever looked at a hiking map of the Rocky Mountains, you have seen contour lines.

I use the contour() and contourf() functions in Matplotlib when I want to show levels or “isobars” in my 2D Python arrays.

This is particularly useful if you are a Python developer working on environmental or geographical software.

import matplotlib.pyplot as plt
import numpy as np

# Creating a grid for a mountain-like shape
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R) # Simulating wave-like terrain

# Creating a filled contour plot
plt.figure(figsize=(8, 6))
cp = plt.contourf(X, Y, Z, cmap='terrain')

# Adding a color bar and title
plt.colorbar(cp, label='Elevation Level (Meters)')
plt.title('Topographic Elevation Map of a National Park')
plt.xlabel('Longitude')
plt.ylabel('Latitude')

plt.show()

I executed the above example code and added the screenshot below.

How to Plot Matplotlib 2D NumPy Array

I like contourf() (the ‘f’ stands for filled) because it provides a more intuitive visual of the “height” of the data compared to just lines.

Method 4: Visualize 2D Arrays with 3D Surfaces

When a 2D heatmap isn’t enough to convey the depth of the data, I switch to a 3D perspective.

This is very common when I present data to stakeholders who want to see the “peaks and valleys” of business metrics, like quarterly sales growth across different US states.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

# Setting up the 3D projection
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

# Data for a 3D surface (Example: Economic growth spikes)
x = np.outer(np.linspace(-3, 3, 30), np.ones(30))
y = x.copy().T
z = np.cos(x ** 2 + y ** 2)

# Plotting the surface
surf = ax.plot_surface(x, y, z, cmap='magma', edgecolor='none')

# Customizing the 3D view
ax.set_title('3D Surface Projection of US Economic Growth Cycles')
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)

plt.show()

Note that I use the projection=’3d’ argument. This changes the entire context of the plot, allowing for rotation and perspective.

Tips for Better Matplotlib 2D Plots

Over the years, I have learned a few tricks that make your Python plots look much more professional:

  1. Choose the Right Colormap: Never use “jet” if you can avoid it. I recommend “viridis” or “magma” because they are perceptually uniform (easier for the human brain to process).
  2. Aspect Ratio: In imshow(), use aspect=’auto’ if your array isn’t a square, but you want it to fill the plot area.
  3. Colorbars: Always add a colorbar. A plot without a scale is just a pretty picture, not data visualization.
  4. DPI Settings: If you are saving these for a presentation, use plt.savefig(‘plot.png’, dpi=300) to ensure the lines are crisp.

Common Issues and Solutions

One problem I often see beginners face is the orientation of the 2D array. By default, Matplotlib might plot the first row of your array at the top.

If your data represents coordinates where (0,0) should be at the bottom-left (like a standard graph), use the origin=’lower’ parameter in imshow().

Another issue is handling missing data. If your NumPy array has NaN values, Matplotlib will usually leave those spots blank (white). I suggest using a masked array to handle these if you want to give them a specific color.

I hope this guide helps you visualize your 2D arrays more effectively. Matplotlib is a deep library, but mastering these few methods will cover 90% of your data visualization needs in Python.

It is often a good idea to experiment with different colormaps and interpolation methods to see which one tells the best story for your specific data.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.