KDE Plot
Sleep Duration Distribution
KDE showing nightly sleep hours with health zone indicators.
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
np.random.seed(50)
# Sleep hours distribution
sleep = np.random.normal(7, 1.5, 1000)
sleep = sleep[(sleep > 3) & (sleep < 12)]
kde = stats.gaussian_kde(sleep)
x = np.linspace(3, 12, 500)
y = kde(x)
fig, ax = plt.subplots(figsize=(12, 6), facecolor='#0a0a0f')
ax.set_facecolor('#0a0a0f')
# Fill with mint color
ax.fill_between(x, y, alpha=0.4, color='#27F5B0')
ax.plot(x, y, color='#27F5B0', linewidth=3)
ax.plot(x, y, color='#27F5B0', linewidth=8, alpha=0.2) # Glow
# Health zones
ax.axvspan(7, 9, alpha=0.2, color='#6CF527', label='Optimal (7-9h)')
ax.axvspan(5, 7, alpha=0.15, color='#F5B027', label='Suboptimal')
ax.axvspan(3, 5, alpha=0.15, color='#F5276C', label='Sleep Deprived')
# Statistics
mean_sleep = np.mean(sleep)
ax.axvline(mean_sleep, color='white', linestyle='--', linewidth=2)
ax.text(mean_sleep+0.1, max(y)*0.9, f'Mean: {mean_sleep:.1f}h', color='white', fontsize=11, fontweight='bold')
ax.set_xlabel('Sleep Duration (hours)', fontsize=12, color='white', fontweight='500')
ax.set_ylabel('Density', fontsize=12, color='white', fontweight='500')
ax.set_title('Nightly Sleep Duration Distribution', fontsize=16, color='white', fontweight='bold', pad=15)
ax.tick_params(colors='white', labelsize=10)
for spine in ax.spines.values():
spine.set_color('#334155')
ax.legend(loc='upper right', facecolor='#1e293b', edgecolor='#334155', labelcolor='white')
ax.grid(True, alpha=0.1, color='white')
ax.set_xlim(3, 12)
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Statistical
☕