Create 2D Surface Plots with Matplotlib in Python

As a Python developer, I’ve worked extensively with data visualization tools. Among them, Matplotlib remains my go-to library for creating insightful graphics. One of the most powerful yet sometimes overlooked visualizations is the 2D surface plot.

Today, I’ll share practical methods to create and customize 2D surface plots using Matplotlib, based on real-world projects I’ve tackled, especially those involving US-based datasets like elevation profiles and temperature maps.

Let’s get in.

What is a 2D Surface Plot?

A 2D surface plot is a graphical representation of three-dimensional data where two variables define the x and y axes, and a third variable defines the surface height (z-axis). Unlike 3D surface plots, which can be rotated and viewed from different angles, 2D surface plots are often displayed as color-coded heatmaps or contour maps that provide a top-down view of the surface.

In my experience, these plots are invaluable when you want to visualize spatial data or any metric changing over two variables, like temperature across a geographic area in the USA or sales performance across different regions.

Read Horizontal Line Matplotlib

Method 1: Use imshow() for 2D Surface Plot

One of the simplest ways to create a 2D surface plot in Matplotlib is using the imshow() function in Python. This method is perfect when you have gridded data and want to visualize it as an image with color representing the surface height.

  1. Prepare your data: For example, imagine you have temperature readings across a grid of locations in California.
  2. Import necessary libraries:
import numpy as np
import matplotlib.pyplot as plt
  1. Create or load your 2D data array:
# Simulated temperature data (in Fahrenheit) across a 10x10 grid
temperature_data = np.random.uniform(60, 100, (10, 10))
  1. Plot using imshow():
plt.imshow(temperature_data, cmap='coolwarm', origin='lower')
plt.colorbar(label='Temperature (°F)')
plt.title('California Temperature Heatmap')
plt.xlabel('Longitude Index')
plt.ylabel('Latitude Index')
plt.show()

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

2d surface plot python

imshow() is fast and straightforward. It’s great for quick heatmaps or when you want a pixel-perfect representation of your data grid. The origin='lower' parameter ensures the y-axis starts from the bottom, which is intuitive for geographic data.

Check out Draw a Vertical Line Matplotlib

Method 2: Use contourf() for Filled Contour Plots

For a more refined 2D surface visualization, I often use the Python’s contourf() function. This method draws filled contour lines that represent levels of the third variable, making it easier to interpret gradients and transitions.

  1. Generate meshgrid for coordinates:
x = np.linspace(-125, -114, 100)  # Longitude range in California
y = np.linspace(32, 42, 100)      # Latitude range in California
X, Y = np.meshgrid(x, y)
  1. Create a synthetic elevation function to simulate terrain:
Z = np.sin(0.1 * X) * np.cos(0.1 * Y) * 1000 + 2000  # Elevation in feet
  1. Plot the filled contour:
plt.contourf(X, Y, Z, cmap='terrain')
plt.colorbar(label='Elevation (feet)')
plt.title('California Elevation Map')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()

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

matplotlib plot 2d

contourf() provides a smooth gradient between levels, which is visually appealing and helpful in understanding elevation changes or temperature gradients. It’s especially useful when working with geographic or meteorological data.

Read Matplotlib Two y axes

Method 3: Use pcolormesh() for Large Datasets

When dealing with large datasets, such as satellite imagery or detailed elevation data from the USGS, performance becomes a concern. pcolormesh() is optimized for such cases and can handle non-uniform grids better than imshow().

  1. Create coordinate grids:
x = np.linspace(-125, -114, 500)
y = np.linspace(32, 42, 500)
X, Y = np.meshgrid(x, y)
  1. Simulate some data:
Z = np.exp(-((X + 120)**2 + (Y - 37)**2) / 50) * 3000  # Simulated peak elevation
  1. Plot using pcolormesh():
plt.pcolormesh(X, Y, Z, shading='auto', cmap='viridis')
plt.colorbar(label='Elevation (feet)')
plt.title('Simulated Peak Elevation in California')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()

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

matplotlib 2d plot

It’s faster and more flexible with grid shapes. The shading='auto' option smooths the colors between grid points, improving aesthetics.

Check out Matplotlib Invert y axis

Customize Your 2D Surface Plots

Over the years, I’ve learned that customization is key to making your plots truly useful.

  • Color Maps: Choose colormaps that suit your data context. For temperature, coolwarm or inferno work well. For elevation, terrain or viridis are excellent choices.
  • Color Bars: Always add a color bar with labels to make your plot interpretable.
  • Axis Labels & Titles: Use meaningful labels like longitude and latitude instead of generic axis labels.
  • Gridlines: Adding gridlines can help users identify exact locations.
plt.grid(True, linestyle='--', alpha=0.5)
  • Annotations: You can add markers or annotations for points of interest, such as major cities or landmarks.

Read Put the Legend Outside the Plot in Matplotlib

Bonus: Combine 2D Surface Plots with Real US Data

For a practical example, I once visualized average annual rainfall across the US states using a 2D surface plot. By mapping latitude and longitude to a grid and rainfall data as the surface height, I created a heatmap that clearly showed wetter regions like the Pacific Northwest.

Using publicly available data from NOAA, you can replicate this by:

  1. Downloading gridded climate data.
  2. Processing it into a 2D array.
  3. Visualizing it with imshow(), contourf(), or pcolormesh().

This approach is invaluable for environmental scientists, urban planners, or anyone interested in geographic data analysis.

Creating 2D surface plots with Matplotlib is easy once you understand these methods. Whether you want a quick heatmap or a detailed contour map, Matplotlib offers flexible options to visualize your data effectively.

Try these methods with your US-based datasets. You’ll find that visualizing data in this way can uncover patterns and insights that raw numbers alone can’t reveal.

Other Matplotlib articles you may also like:

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.