Hexbin Plot
Investment Portfolio Analysis
Risk vs return distribution for portfolio optimization with modern light styling.
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
np.random.seed(42)
n_assets = 8000
# Risk (volatility %) and return %
risk = np.random.lognormal(2, 0.6, n_assets)
risk = np.clip(risk, 2, 50)
# Return correlates with risk (with noise)
expected_return = 2 + 0.3 * risk + np.random.normal(0, 3, n_assets)
expected_return = np.clip(expected_return, -10, 40)
fig, ax = plt.subplots(figsize=(10, 8), facecolor='#ffffff')
ax.set_facecolor('#f5f3ff')
colors = ['#f5f3ff', '#ede9fe', '#ddd6fe', '#c4b5fd', '#a78bfa',
'#8b5cf6', '#7c3aed', '#6d28d9', '#5b21b6', '#4c1d95']
cmap = LinearSegmentedColormap.from_list('violet', colors, N=256)
hb = ax.hexbin(risk, expected_return, gridsize=35, cmap=cmap, mincnt=1,
edgecolors='white', linewidths=0.3)
# Efficient frontier approximation
risk_line = np.linspace(5, 40, 100)
frontier = 2 + 0.5 * risk_line - 0.002 * risk_line ** 2 + 5
ax.plot(risk_line, frontier, '-', color='#6d28d9', linewidth=3, alpha=0.9, label='Efficient Frontier')
# Risk-free rate
ax.axhline(y=4, color='#22c55e', linestyle='--', alpha=0.7, linewidth=2, label='Risk-Free Rate')
# Capital Market Line
cml_x = np.linspace(0, 40, 100)
cml_y = 4 + 0.5 * cml_x
ax.plot(cml_x, cml_y, ':', color='#0ea5e9', linewidth=2, alpha=0.8, label='Capital Market Line')
cbar = plt.colorbar(hb, ax=ax, pad=0.02, shrink=0.85)
cbar.set_label('Asset Count', fontsize=11, color='#4c1d95', labelpad=10)
cbar.ax.yaxis.set_tick_params(color='#5b21b6')
cbar.outline.set_edgecolor('#ddd6fe')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#5b21b6', fontsize=9)
ax.set_xlabel('Risk (Volatility %)', fontsize=12, color='#4c1d95', fontweight='600', labelpad=12)
ax.set_ylabel('Expected Return (%)', fontsize=12, color='#4c1d95', fontweight='600', labelpad=12)
ax.set_title('Portfolio Risk-Return Analysis', fontsize=16, color='#2e1065', fontweight='700', pad=20)
ax.tick_params(colors='#5b21b6', labelsize=10, length=0)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#ddd6fe')
ax.spines['bottom'].set_color('#ddd6fe')
ax.legend(loc='lower right', fontsize=9, frameon=True, facecolor='white',
edgecolor='#ddd6fe', labelcolor='#4c1d95')
ax.grid(True, alpha=0.3, color='#ddd6fe', linestyle='-', linewidth=0.5)
ax.set_axisbelow(True)
ax.set_xlim(0, 50)
ax.set_ylim(-10, 40)
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Pairwise Data
More Hexbin Plot examples
☕