How to plot a density map in Python Matplotlib?

A density map is a visualization technique that represents data density using colors across a 2D grid. In Python Matplotlib, we can create density maps using pcolormesh() to display smooth color transitions based on data values.

Steps to Create a Density Map

To plot a density map in Python, we can take the following steps −

  • Create coordinate arrays using numpy.linspace() to define the grid boundaries

  • Generate coordinate matrices using meshgrid() from the coordinate vectors

  • Create density data using mathematical functions (like exponential or Gaussian)

  • Plot the density map using pcolormesh() method

  • Display the figure using show() method

Basic Density Map Example

Here's how to create a simple density map with a Gaussian-like distribution ?

from matplotlib import pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create coordinate arrays
side = np.linspace(-2, 2, 15)
X, Y = np.meshgrid(side, side)

# Create density data (Gaussian-like function)
Z = np.exp(-((X - 1) ** 2 + Y ** 2))

# Plot density map
plt.pcolormesh(X, Y, Z, shading='auto')
plt.colorbar(label='Density')
plt.title('Basic Density Map')
plt.xlabel('X coordinate')
plt.ylabel('Y coordinate')

plt.show()

Advanced Density Map with Custom Colormap

You can enhance the density map by using custom colormaps and adding more detail ?

from matplotlib import pyplot as plt, cm
import numpy as np

# Create higher resolution grid
side = np.linspace(-3, 3, 50)
X, Y = np.meshgrid(side, side)

# Create more complex density function
Z = np.exp(-((X - 0.5) ** 2 + (Y + 0.5) ** 2)) + 0.5 * np.exp(-((X + 1) ** 2 + (Y - 1) ** 2))

# Plot with custom colormap
plt.figure(figsize=(8, 6))
density_plot = plt.pcolormesh(X, Y, Z, shading='auto', cmap='viridis')
plt.colorbar(density_plot, label='Density Value')
plt.title('Advanced Density Map with Custom Colormap')
plt.xlabel('X coordinate')
plt.ylabel('Y coordinate')

plt.show()

Key Parameters

  • shading: Controls how colors are applied ('auto', 'flat', or 'gouraud')

  • cmap: Colormap for the density visualization ('viridis', 'plasma', 'hot', etc.)

  • vmin/vmax: Set minimum and maximum values for color scaling

Conclusion

Density maps in Matplotlib use pcolormesh() to visualize data density through color gradients. Use higher resolution grids and custom colormaps to create more detailed and visually appealing density visualizations.

Updated on: 2026-03-25T19:50:15+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements