2D Histogram
Stock vs Market Returns
Beta analysis with return density distribution
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
# Financial returns data
np.random.seed(42)
n_days = 8000
# Market returns (S&P 500 proxy)
market = np.random.normal(0.04, 1.2, n_days)
market = np.clip(market, -8, 8)
# Stock returns with beta relationship
beta = 1.3
alpha = 0.02
stock = alpha + beta * market + np.random.normal(0, 0.8, n_days)
stock = np.clip(stock, -12, 12)
# Finance dark theme
plt.style.use('dark_background')
fig, ax = plt.subplots(figsize=(10, 8))
fig.patch.set_facecolor('#0a0c10')
ax.set_facecolor('#0a0c10')
# Custom colormap - finance green-gold
colors = ['#0a0c10', '#0a1a15', '#0a2a20', '#1a4a30', '#2a6a40',
'#4a8a50', '#6aaa60', '#90ca70', '#b0ea80', '#d0ff90', '#f0ffb0']
cmap = LinearSegmentedColormap.from_list('finance', colors, N=256)
# 2D histogram
h = ax.hist2d(market, stock, bins=50, cmap=cmap, cmin=1)
# Zero lines
ax.axhline(y=0, color='#4a8a50', linestyle='-', alpha=0.4, linewidth=1)
ax.axvline(x=0, color='#4a8a50', linestyle='-', alpha=0.4, linewidth=1)
# Beta regression line
x_line = np.linspace(-8, 8, 100)
y_line = alpha + beta * x_line
ax.plot(x_line, y_line, '-', color='#d0ff90', linewidth=2.5, alpha=0.9, label=f'Beta = {beta}')
# Market line (beta = 1)
ax.plot(x_line, x_line, '--', color='#90ca70', linewidth=1.5, alpha=0.6, label='Market (Beta=1)')
# Styled colorbar
cbar = plt.colorbar(h[3], ax=ax, pad=0.02, shrink=0.85)
cbar.ax.set_facecolor('#0a0c10')
cbar.set_label('Trading Days', fontsize=11, color='#b0d0a0', labelpad=10)
cbar.ax.yaxis.set_tick_params(color='#b0d0a0')
cbar.outline.set_edgecolor('#2a4030')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#b0d0a0', fontsize=9)
# Labels
ax.set_xlabel('Market Return (%)', fontsize=13, color='#b0d0a0', fontweight='600', labelpad=10)
ax.set_ylabel('Stock Return (%)', fontsize=13, color='#b0d0a0', fontweight='600', labelpad=10)
ax.set_title('Stock vs Market Returns (Beta Analysis)', fontsize=16, color='white',
fontweight='bold', pad=20)
# Style axes
ax.tick_params(colors='#90b080', labelsize=10, length=0)
for spine in ax.spines.values():
spine.set_visible(False)
ax.legend(loc='upper left', fontsize=10, facecolor='#1a2a20', edgecolor='#2a4030',
labelcolor='#b0d0a0', framealpha=0.9)
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Statistical
More 2D Histogram examples
☕