Violin Plot

Violin with Statistics

Annotated with mean, standard deviation, and median

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

# Data
np.random.seed(42)
groups = ['Model A', 'Model B', 'Model C']
data = [np.random.normal(85, 5, 200),
        np.random.normal(78, 8, 200),
        np.random.normal(92, 3, 200)]

# Colors
colors = ['#3B82F6', '#F59E0B', '#10B981']

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

vp = ax.violinplot(data, positions=range(len(data)), widths=0.7,
                   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(2)
    body.set_alpha(0.75)

# Add statistics annotations
for i, d in enumerate(data):
    mean = np.mean(d)
    std = np.std(d)
    median = np.median(d)
    
    # Mean line
    ax.hlines(mean, i - 0.25, i + 0.25, color='white', linewidth=3)
    
    # Stats box
    stats_text = 'mean=%.1f\nstd=%.1f\nmed=%.1f' % (mean, std, median)
    ax.annotate(stats_text, xy=(i + 0.4, mean),
                fontsize=9, color='#374151', va='center',
                bbox=dict(boxstyle='round,pad=0.3', facecolor='white',
                         edgecolor='#E5E7EB', alpha=0.9))

# Customize axes
ax.set_xticks(range(len(groups)))
ax.set_xticklabels(groups, fontsize=11, fontweight='500')
ax.set_ylabel('Accuracy (%)', fontsize=12, fontweight='500', color='#374151')
ax.set_xlim(-0.5, len(groups) + 0.3)

# 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