Explain Codes LogoExplain Codes Logo

Plotting a 2D heatmap

python
matplotlib
data-visualization
heatmap
Nikita BarsukovbyNikita Barsukov·Mar 2, 2025
TLDR

To quickly get a 2D heatmap, use matplotlib's imshow function:

import matplotlib.pyplot as plt import numpy as np # Generate a random 2D array (plotting real-world data would be less random) data = np.random.rand(10, 10) # Who knows? This could be the temperatures of 10 city blocks! plt.imshow(data, cmap='viridis') # "Viridis" is a colormap that takes a hot bath every day to look clean and reflective. plt.colorbar() # If it were me, I'd ask for the color key too. plt.show() # Now, bask in the glory of your heatmap!

In place of np.random.rand(10, 10), substitute data with your actual 2D array.

Customization: More than just a pretty face

Before going all-out decorator mode, make sure you've got the necessary libraries:

# We are plotting a graph, not baking a cake! import matplotlib.pyplot as plt import numpy as np

Let's look at some nifty customization tools at your disposal:

  • Colormap selection: Use cmap to choose a color map theme. From 'hot' for heatmaps to 'winter' for cooler data.
  • Interpolation methods: The interpolation parameter helps in pixel representation, 'nearest' gives a raw pixel view, others, a smoothie.
  • Data normalization: Scale your data between 0 and 1 to ensure accuracy.
  • Nonuniform data: With pcolor and pcolormesh, you can plot data doing the limbo (irregular spacing).
  • Contours: If you stare at your data long enough, and it looks continuous, contour plots are an alternative.

Real-world applications

Imagine generating a heatmap from a CSV file because, let's face it, we need more heats and less spams:

import pandas as pd # Load your CSV data into a DataFrame df = pd.read_csv('data.csv') # Convert DataFrame to a NumPy array data = df.values plt.imshow(data, cmap='hot') plt.colorbar() plt.show()

If your data has a mind of its own and is non-rectangular, interpolate it onto a regular grid:

from scipy.interpolate import griddata # Imagine 'points' as an array of (x,y) pairs and 'values' are their clingy z values grid_x, grid_y = np.mgrid[min_x:max_x:100j, min_y:max_y:100j] grid_z = griddata(points, values, (grid_x, grid_y), method='cubic') plt.imshow(grid_z.T, cmap='hot', origin='lower') plt.colorbar() plt.show()

Seaborn: Heatmap fashionista

Meet Seaborn. It's where matplotlib goes to get its hair done:

import seaborn as sns # Heatmap with Seaborn ax = sns.heatmap(data, vmax=1.0, square=True, cmap='coolwarm') plt.show()

Add some extra flair with:

  • sns.axes_style(): Break the monotony. Customize your axes designs.
  • Focal study: Shine your spotlight on specific regions of your matrix.
  • Annotation: Because who wouldn’t like some footnotes on their heatmap!

Anticipating roadblocks

Anticipate some potential bumps along your heatmap journey:

  • Distorted aspect ratios: Set your aspect to 'auto' or make adjustments to the figure size.
  • Inconsistent colors: Validate data normalization and cmap selection for accurate colors.
  • Large datasets: When dealing with Godzilla-sized datasets, focus on optimizing data types or plot in chunks.