Violin Plot

Overlapping Violin Plot

Before/after distribution overlay comparison

Output
Overlapping Violin Plot
Python
import matplotlib.pyplot as plt
import numpy as np

# Data
np.random.seed(42)
before = np.random.normal(50, 12, 500)
after = np.random.normal(62, 10, 500)

# Colors
color_before = '#EF4444'
color_after = '#10B981'

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

# Plot both violins at same position
vp1 = ax.violinplot([before], positions=[0], widths=1.2,
                    showmeans=False, showmedians=False, showextrema=False)
vp2 = ax.violinplot([after], positions=[0], widths=1.2,
                    showmeans=False, showmedians=False, showextrema=False)

for body in vp1['bodies']:
    body.set_facecolor(color_before)
    body.set_edgecolor(color_before)
    body.set_linewidth(2)
    body.set_alpha(0.4)

for body in vp2['bodies']:
    body.set_facecolor(color_after)
    body.set_edgecolor(color_after)
    body.set_linewidth(2)
    body.set_alpha(0.4)

# Add median markers
ax.scatter(0, np.median(before), c=color_before, s=150, marker='|',
           linewidth=3, zorder=5, label=f'Before (median: {np.median(before):.1f})')
ax.scatter(0, np.median(after), c=color_after, s=150, marker='|',
           linewidth=3, zorder=5, label=f'After (median: {np.median(after):.1f})')

# Legend
ax.legend(loc='upper right', frameon=False, fontsize=11)

# Add improvement annotation
improvement = np.median(after) - np.median(before)
ax.annotate(f'+{improvement:.1f}', xy=(0.15, np.median(after)),
            fontsize=14, fontweight='bold', color=color_after)

# Customize axes
ax.set_xticks([0])
ax.set_xticklabels(['Performance Score'], fontsize=12, fontweight='500')
ax.set_ylabel('Score', fontsize=12, fontweight='500', color='#374151')
ax.set_xlim(-1, 1)

# 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