Contour Plots and Heatmaps

Back

Loading concept...

🗺️ Contour Plots & Heatmaps: Painting with Numbers

The Story: Imagine You’re a Weather Reporter!

Have you ever seen those colorful weather maps on TV? The ones that show where it’s hot (red), warm (yellow), and cold (blue)? That’s exactly what contour plots and heatmaps do!

Think of it like this: You have a big playground, and you want to show where all the puddles are after rain. Instead of pointing to each puddle, you could paint the ground — deep blue for deep puddles, light blue for shallow ones, and no color where it’s dry.

That’s what we’re learning today! 🎨


🏔️ Part 1: Contour Plot Basics

What is a Contour Plot?

Imagine you’re looking at a mountain from a helicopter above. You see circles that show “same height” — like the lines on a topographic hiking map!

A contour plot draws lines where values are EQUAL.

import matplotlib.pyplot as plt
import numpy as np

# Create a grid (like graph paper)
x = np.linspace(-3, 3, 50)
y = np.linspace(-3, 3, 50)
X, Y = np.meshgrid(x, y)

# Create "heights" (like a hill)
Z = np.sin(X) * np.cos(Y)

# Draw the contour lines!
plt.contour(X, Y, Z)
plt.title('My First Contour Plot!')
plt.show()

What Just Happened?

  1. np.meshgrid = Creates a grid of X and Y coordinates (like graph paper squares)
  2. Z = The “height” at each point (our hill shape)
  3. plt.contour = Draws lines connecting equal heights

Real World: Think of each line as a hiking trail that stays perfectly flat — no going up or down!


🌈 Part 2: Filled Contour Plot

Lines are Nice, But Colors are Better!

What if instead of just lines, we fill the spaces between with beautiful colors?

# Same grid as before
X, Y = np.meshgrid(
    np.linspace(-3, 3, 50),
    np.linspace(-3, 3, 50)
)
Z = np.sin(X) * np.cos(Y)

# NOW with colors filled in!
plt.contourf(X, Y, Z, cmap='viridis')
plt.colorbar()  # Shows what colors mean
plt.title('Filled Contour - So Pretty!')
plt.show()

The Magic Word: contourf

See that little f at the end? It stands for “filled”!

Command What It Does
contour Draws lines only
contourf Fills with colors

Colorbar = A legend that tells you “purple means low, yellow means high”


🎨 Part 3: Contour Customization

Make It YOUR Way!

You can control everything:

X, Y = np.meshgrid(
    np.linspace(-3, 3, 50),
    np.linspace(-3, 3, 50)
)
Z = X**2 + Y**2  # A bowl shape!

# Custom levels and colors
levels = [0, 2, 4, 6, 8, 10]
plt.contourf(X, Y, Z, levels=levels,
             cmap='coolwarm')
plt.contour(X, Y, Z, levels=levels,
            colors='black', linewidths=0.5)
plt.colorbar()
plt.title('Custom Contour Levels')
plt.show()

Customization Options

Option What It Does Example
levels How many lines/zones levels=10 or [0,2,4,6]
cmap Color scheme 'hot', 'cool', 'viridis'
colors Line colors 'black', 'white'
linewidths Line thickness 0.5, 1, 2

Pro Tip: Layer contourf AND contour together — colors for areas, black lines for clarity!


🔥 Part 4: Heatmap with imshow

The Simplest Heatmap

Now forget about hills and mountains. Imagine you have a checkerboard and each square has a temperature. How do you show this?

imshow treats your data like a picture!

# Simple 5x5 grid of numbers
data = np.array([
    [1, 2, 3, 4, 5],
    [2, 3, 4, 5, 6],
    [3, 4, 5, 6, 7],
    [4, 5, 6, 7, 8],
    [5, 6, 7, 8, 9]
])

plt.imshow(data, cmap='hot')
plt.colorbar()
plt.title('Heatmap with imshow')
plt.show()

What Makes imshow Special?

  • Each cell = one pixel of color
  • Fast and simple for grid data
  • Origin starts at TOP-LEFT (like reading a book!)
# To flip it (math-style, origin at bottom):
plt.imshow(data, cmap='hot', origin='lower')

🧱 Part 5: Heatmap with pcolormesh

When You Need More Control

pcolormesh is like imshow’s smarter cousin. It lets you define exactly where each cell is.

# Create X, Y coordinates
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 1, 2, 3, 4, 5])

# 5x5 data grid
data = np.random.rand(5, 5) * 10

plt.pcolormesh(x, y, data, cmap='Blues')
plt.colorbar()
plt.title('Heatmap with pcolormesh')
plt.show()

imshow vs pcolormesh

Feature imshow pcolormesh
Speed Faster Slightly slower
Grid type Must be regular Can be irregular!
Coordinates Automatic You define them
Best for Images, simple grids Science data, custom grids

When to use pcolormesh?

  • Your X or Y spacing is NOT equal
  • You need precise coordinate labels
  • You’re plotting real scientific data

🎯 Quick Summary

graph TD A["Want to show 3D data<br>on 2D surface?"] --> B{What style?} B -->|Lines only| C["contour"] B -->|Filled colors| D["contourf"] B -->|Simple grid| E["imshow"] B -->|Custom coordinates| F["pcolormesh"] C --> G["Add levels for more lines"] D --> G E --> H["Use cmap for colors"] F --> H

🚀 You Did It!

You now know how to:

✅ Draw contour lines like a map maker ✅ Fill contours with beautiful colorsCustomize levels, colors, and line styles ✅ Create heatmaps with imshow for simple grids ✅ Use pcolormesh when you need precise control

Remember: Contour plots and heatmaps are just fancy ways to paint numbers! Low values get one color, high values get another. That’s it! 🎨


💡 One Last Tip

When choosing between these tools, ask yourself:

“Am I showing continuous terrain (contour) or discrete boxes (heatmap)?”

  • Weather maps, elevation → Contour
  • Correlation matrices, pixel data → Heatmap

Now go make some beautiful visualizations! 🌟

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.