Area Chart

Bayesian Posterior

Prior vs posterior distribution comparison - R style

Output
Bayesian Posterior
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

x = np.linspace(-2, 8, 200)
prior = stats.norm.pdf(x, 2, 2)
likelihood_effect = stats.norm.pdf(x, 4.5, 1)
posterior = stats.norm.pdf(x, 3.8, 0.8)

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

ax.fill_between(x, 0, prior, alpha=0.3, color='#F5B027', label='Prior')
ax.fill_between(x, 0, posterior, alpha=0.5, color='#27D3F5', label='Posterior')
ax.plot(x, prior, color='#F5B027', linewidth=2, linestyle='--')
ax.plot(x, posterior, color='#27D3F5', linewidth=2.5)

# Credible interval
ci_low, ci_high = 3.8 - 1.96*0.8, 3.8 + 1.96*0.8
ax.axvspan(ci_low, ci_high, alpha=0.15, color='#27D3F5')
ax.axvline(3.8, color='#F5276C', linewidth=2, linestyle=':', label=f'MAP: 3.8')

ax.text(0.95, 0.95, f'95% CI: [{ci_low:.2f}, {ci_high:.2f}]', transform=ax.transAxes,
        color='#1f2937', fontsize=10, ha='right', va='top',
        bbox=dict(boxstyle='round', facecolor='#f3f4f6', edgecolor='#e5e7eb'))

ax.set_xlabel('Parameter θ', color='#1f2937', fontsize=11, fontweight='500')
ax.set_ylabel('Density', color='#1f2937', fontsize=11, fontweight='500')
ax.set_title('Bayesian Parameter Estimation', color='#1f2937', fontsize=13, fontweight='600', pad=15)
ax.tick_params(colors='#374151', labelsize=9)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#e5e7eb')
ax.spines['bottom'].set_color('#e5e7eb')
ax.yaxis.grid(True, color='#f3f4f6', linewidth=0.8)
ax.legend(facecolor='#ffffff', edgecolor='#e5e7eb', labelcolor='#1f2937')
ax.set_xlim(-2, 8)

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Basic Charts

Did this help you?

Support PyLucid to keep it free & growing

Support