How to plot a 3D density map in Python with Matplotlib?

A 3D density map visualizes data density across a 2D plane using colors to represent values at different coordinates. Python's Matplotlib provides the pcolormesh() function to create these density maps efficiently.

Steps to Create a 3D Density Map

To plot a 3D density map in Python with matplotlib, we can take the following steps:

  • Create coordinate data using numpy.linspace() to generate evenly spaced points

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

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

  • Plot the density map using pcolormesh() method with color mapping

  • Display the figure using show() method

Example

Let's create a 3D density map using an exponential function ?

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 using exponential function
Z = np.exp(-((X - 1) ** 2 + Y ** 2))

# Create the density map
plt.pcolormesh(X, Y, Z, shading='auto')
plt.colorbar(label='Density')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('3D Density Map')
plt.show()

Enhanced Example with Custom Colormap

You can customize the appearance using different colormaps ?

from matplotlib import pyplot as plt
import numpy as np

# Create finer grid for smoother visualization
side = np.linspace(-3, 3, 50)
X, Y = np.meshgrid(side, side)

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

# Plot with custom colormap
plt.figure(figsize=(8, 6))
density_plot = plt.pcolormesh(X, Y, Z, shading='gouraud', cmap='plasma')
plt.colorbar(density_plot, label='Density Value')
plt.xlabel('X coordinate')
plt.ylabel('Y coordinate')
plt.title('Enhanced 3D Density Map with Custom Colormap')
plt.show()

Key Parameters

Important parameters for pcolormesh():

  • shading: Controls interpolation ('auto', 'flat', 'gouraud')

  • cmap: Colormap selection ('viridis', 'plasma', 'coolwarm', etc.)

  • alpha: Transparency level (0.0 to 1.0)

  • vmin/vmax: Sets the color scale range

Conclusion

Use pcolormesh() with meshgrid() to create effective 3D density maps in Python. Customize with different colormaps and shading options for better visualization of your data patterns.

Updated on: 2026-03-25T19:44:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements