Violin Plot

Violin with Confidence Interval

Violin plot with 95% confidence intervals

Output
Violin with Confidence Interval
Python
import matplotlib.pyplot as plt
import numpy as np

# Data
np.random.seed(42)
experiments = ['Exp 1', 'Exp 2', 'Exp 3', 'Exp 4']
data = [np.random.normal(loc, 1.5, 100) for loc in [5, 7, 6, 8]]

# Colors
colors = ['#6366F1', '#8B5CF6', '#A855F7', '#D946EF']

# Create figure
fig, ax = plt.subplots(figsize=(10, 6), facecolor='white')

vp = ax.violinplot(data, positions=range(len(data)), widths=0.6,
                   showmeans=False, showmedians=False, showextrema=False)

for i, body in enumerate(vp['bodies']):
    body.set_facecolor(colors[i])
    body.set_edgecolor('white')
    body.set_linewidth(1.5)
    body.set_alpha(0.5)

# Add 95% CI and mean
for i, d in enumerate(data):
    mean = np.mean(d)
    sem = np.std(d) / np.sqrt(len(d))
    ci_95 = 1.96 * sem
    
    # CI bar
    ax.errorbar(i, mean, yerr=ci_95, color=colors[i], capsize=8,
                capthick=2, linewidth=2, zorder=5)
    
    # Mean dot
    ax.scatter(i, mean, c='white', s=100, zorder=6,
               edgecolor=colors[i], linewidth=2)
    
    # CI annotation
    ci_text = '95%% CI\n+/-%.2f' % ci_95
    ax.annotate(ci_text, xy=(i + 0.35, mean),
                fontsize=9, color='#6B7280', va='center')

# Customize axes
ax.set_xticks(range(len(experiments)))
ax.set_xticklabels(experiments, fontsize=11, fontweight='500')
ax.set_ylabel('Effect Size', fontsize=12, fontweight='500', color='#374151')

# Clean styling
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.tick_params(colors='#6B7280', labelsize=10)
ax.yaxis.grid(True, linestyle='--', alpha=0.3, color='#9CA3AF')

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Statistical

Did this help you?

Support PyLucid to keep it free & growing

Support