Histogram

2D Histogram Heatmap

Joint distribution of two variables.

Output
2D Histogram Heatmap
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

COLORS = {
    'background': '#FFFFFF',
    'text': '#1E293B',
    'text_muted': '#64748B',
    'grid': '#E2E8F0'
}

np.random.seed(42)
x = np.random.normal(50, 15, 2000)
y = 0.8 * x + np.random.normal(0, 10, 2000)

# Professional gray-to-red colormap
colors_cmap = ['#F8FAFC', '#E2E8F0', '#94A3B8', '#64748B', '#475569', '#374151', '#1F2937']
cmap = LinearSegmentedColormap.from_list('gray_pro', colors_cmap)

fig, ax = plt.subplots(figsize=(10, 8), dpi=100)
ax.set_facecolor(COLORS['background'])
fig.patch.set_facecolor(COLORS['background'])

h = ax.hist2d(x, y, bins=30, cmap=cmap)
cbar = plt.colorbar(h[3], ax=ax, pad=0.02)
cbar.set_label('Count', fontsize=10, color=COLORS['text'])
cbar.ax.tick_params(colors=COLORS['text_muted'], labelsize=8)

# Correlation line
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
x_line = np.linspace(min(x), max(x), 100)
ax.plot(x_line, p(x_line), color='#DC2626', linewidth=2, linestyle='--', label=f'r = {np.corrcoef(x, y)[0,1]:.2f}')

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color(COLORS['grid'])
ax.spines['bottom'].set_color(COLORS['grid'])
ax.tick_params(axis='both', colors=COLORS['text_muted'], labelsize=9, length=0, pad=8)
ax.set_xlabel('Variable X', fontsize=10, color=COLORS['text'], labelpad=10)
ax.set_ylabel('Variable Y', fontsize=10, color=COLORS['text'], labelpad=10)
ax.legend(loc='upper left', frameon=False, fontsize=10, labelcolor=COLORS['text'])

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Basic Charts

Did this help you?

Support PyLucid to keep it free & growing

Support