2D Histogram
Traffic Flow Density
Urban transportation analysis showing vehicle speed vs traffic density patterns.
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
# Traffic data
np.random.seed(42)
n_samples = 12000
density = np.random.exponential(25, n_samples)
density = np.clip(density, 5, 150)
max_speed, jam_density = 120, 180
speed = max_speed * (1 - density / jam_density) + np.random.normal(0, 8, n_samples)
speed = np.clip(speed, 0, 130)
# Urban night theme
plt.style.use('dark_background')
fig, ax = plt.subplots(figsize=(10, 8))
fig.patch.set_facecolor('#0a0a14')
ax.set_facecolor('#0a0a14')
# Custom colormap - traffic lights
colors = ['#0a0a14', '#101828', '#182838', '#204050', '#286068',
'#308080', '#40a090', '#50c0a0', '#70e0b0', '#a0ffc0', '#d0ffe0']
cmap = LinearSegmentedColormap.from_list('traffic', colors, N=256)
# 2D histogram
h = ax.hist2d(density, speed, bins=50, cmap=cmap, cmin=1)
# Flow regimes
ax.axvline(x=30, color='#50c0a0', linestyle='--', alpha=0.7, linewidth=1.5, label='Free Flow')
ax.axvline(x=70, color='#ffa502', linestyle=':', alpha=0.7, linewidth=1.5, label='Congested')
ax.axvline(x=100, color='#ff6b6b', linestyle='--', alpha=0.7, linewidth=1.5, label='Jam')
# Greenshields curve
x_theory = np.linspace(5, 150, 100)
y_theory = max_speed * (1 - x_theory / jam_density)
ax.plot(x_theory, y_theory, '-', color='#a0ffc0', linewidth=2.5, alpha=0.8, label='Greenshields Model')
# Styled colorbar
cbar = plt.colorbar(h[3], ax=ax, pad=0.02, shrink=0.85)
cbar.ax.set_facecolor('#0a0a14')
cbar.set_label('Observations', fontsize=11, color='#a0e0c0', labelpad=10)
cbar.ax.yaxis.set_tick_params(color='#a0e0c0')
cbar.outline.set_edgecolor('#2a4040')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#a0e0c0', fontsize=9)
ax.set_xlabel('Density (vehicles/km)', fontsize=13, color='#a0e0c0', fontweight='600', labelpad=10)
ax.set_ylabel('Speed (km/h)', fontsize=13, color='#a0e0c0', fontweight='600', labelpad=10)
ax.set_title('Fundamental Diagram of Traffic Flow', fontsize=16, color='white', fontweight='bold', pad=20)
ax.tick_params(colors='#80c0a0', labelsize=10, length=0)
for spine in ax.spines.values():
spine.set_visible(False)
ax.legend(loc='upper right', fontsize=9, facecolor='#1a2830', edgecolor='#2a4040', labelcolor='#a0e0c0')
ax.set_ylim(0, 140)
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Statistical
More 2D Histogram examples
☕