How can I render 3D histograms in Python using Matplotlib?

A 3D histogram visualizes the frequency distribution of data in three-dimensional space using bars. Matplotlib's bar3d() method creates 3D bar plots that can represent histogram data with height, width, and depth dimensions.

Basic 3D Histogram

Here's how to create a basic 3D histogram using sample data ?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Set figure size
plt.rcParams["figure.figsize"] = [10, 8]
plt.rcParams["figure.autolayout"] = True

# Create figure and 3D subplot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Define positions and dimensions
x_pos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_pos = [5, 6, 7, 8, 2, 5, 6, 3, 7, 2]
z_pos = np.zeros(10)  # Base level

# Bar dimensions
dx = np.ones(10)      # Width
dy = np.ones(10)      # Depth
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # Heights

# Create 3D bars
ax.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color='skyblue', alpha=0.8)

# Add labels
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position') 
ax.set_zlabel('Frequency')
ax.set_title('3D Histogram Example')

plt.show()

3D Histogram with Random Data

Creating a more realistic histogram from random data distribution ?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Generate random data
np.random.seed(42)
data_x = np.random.normal(50, 15, 1000)
data_y = np.random.normal(60, 20, 1000)

# Create 2D histogram bins
hist, x_edges, y_edges = np.histogram2d(data_x, data_y, bins=10)

# Create coordinate arrays for bar positions
x_pos, y_pos = np.meshgrid(x_edges[:-1], y_edges[:-1], indexing='ij')
x_pos = x_pos.ravel()
y_pos = y_pos.ravel()
z_pos = np.zeros_like(x_pos)

# Bar dimensions
dx = (x_edges[1] - x_edges[0]) * 0.8
dy = (y_edges[1] - y_edges[0]) * 0.8
dz = hist.ravel()

# Create 3D plot
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection='3d')

# Create bars with color mapping
colors = plt.cm.viridis(dz / dz.max())
ax.bar3d(x_pos, y_pos, z_pos, dx, dy, dz, color=colors, alpha=0.8)

ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')
ax.set_zlabel('Frequency')
ax.set_title('3D Histogram of Random Data')

plt.show()

Customized 3D Histogram

Adding colors, transparency, and styling options ?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Sample data
categories = ['A', 'B', 'C', 'D', 'E']
values_2020 = [23, 45, 56, 78, 32]
values_2021 = [34, 56, 67, 89, 43]

# Create positions
x_pos = np.arange(len(categories))
y_pos = [0, 1]  # Two time periods

# Prepare data for 3D bars
x_3d = []
y_3d = []
z_3d = []
dx_3d = []
dy_3d = []
dz_3d = []
colors = []

for i, cat in enumerate(categories):
    # 2020 data
    x_3d.append(i)
    y_3d.append(0)
    z_3d.append(0)
    dx_3d.append(0.4)
    dy_3d.append(0.4)
    dz_3d.append(values_2020[i])
    colors.append('lightblue')
    
    # 2021 data  
    x_3d.append(i)
    y_3d.append(0.5)
    z_3d.append(0)
    dx_3d.append(0.4)
    dy_3d.append(0.4)
    dz_3d.append(values_2021[i])
    colors.append('orange')

# Create plot
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')

ax.bar3d(x_3d, y_3d, z_3d, dx_3d, dy_3d, dz_3d, color=colors, alpha=0.7)

# Customize axes
ax.set_xticks(range(len(categories)))
ax.set_xticklabels(categories)
ax.set_yticks([0.2, 0.7])
ax.set_yticklabels(['2020', '2021'])
ax.set_xlabel('Categories')
ax.set_ylabel('Year')
ax.set_zlabel('Values')
ax.set_title('Comparative 3D Histogram')

plt.show()

Key Parameters

Parameter Description Example
x, y, z Bottom corner positions [1, 2, 3], [4, 5, 6], [0, 0, 0]
dx, dy, dz Width, depth, height 0.8, 0.8, [10, 20, 15]
color Bar colors 'red', ['blue', 'green']
alpha Transparency 0.8 (0=transparent, 1=opaque)

Conclusion

Use bar3d() to create 3D histograms with customizable dimensions and colors. Combine with histogram2d() for data binning and color mapping for enhanced visualization.

Updated on: 2026-03-25T21:53:05+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements