Area Chart

Kernel Density Estimation

Distribution density with confidence ribbon - R style

Output
Kernel Density Estimation
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

np.random.seed(42)
data = np.concatenate([np.random.normal(25, 5, 500), np.random.normal(45, 8, 300)])
x = np.linspace(0, 70, 200)
kde = stats.gaussian_kde(data)
density = kde(x)

# Bootstrap CI
n_boot = 100
densities = []
for _ in range(n_boot):
    sample = np.random.choice(data, size=len(data), replace=True)
    kde_boot = stats.gaussian_kde(sample)
    densities.append(kde_boot(x))
densities = np.array(densities)
ci_low = np.percentile(densities, 2.5, axis=0)
ci_high = np.percentile(densities, 97.5, axis=0)

fig, ax = plt.subplots(figsize=(10, 6), facecolor='#0a0a0f')
ax.set_facecolor('#0a0a0f')

ax.fill_between(x, ci_low, ci_high, alpha=0.3, color='#27D3F5', label='95% CI')
ax.fill_between(x, 0, density, alpha=0.5, color='#27D3F5')
ax.plot(x, density, color='#27D3F5', linewidth=2)

# Mean and median lines
ax.axvline(np.mean(data), color='#F5276C', linewidth=2, linestyle='--', label=f'Mean: {np.mean(data):.1f}')
ax.axvline(np.median(data), color='#6CF527', linewidth=2, linestyle=':', label=f'Median: {np.median(data):.1f}')

ax.set_xlabel('Value', color='white', fontsize=11, fontweight='500')
ax.set_ylabel('Density', color='white', fontsize=11, fontweight='500')
ax.set_title('Kernel Density Estimation with Bootstrap CI', color='white', fontsize=13, fontweight='600', pad=15)
ax.tick_params(colors='#888888', labelsize=9)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#333333')
ax.spines['bottom'].set_color('#333333')
ax.yaxis.grid(True, color='#1a1a2e', linewidth=0.5, alpha=0.5)
ax.legend(facecolor='#0a0a0f', edgecolor='#333333', labelcolor='white', framealpha=0.9)
ax.set_xlim(0, 70)

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Basic Charts

Did this help you?

Support PyLucid to keep it free & growing

Support