Violin Plot

Grouped Violin Plot

Year-over-year comparison across multiple regions

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

# Data
np.random.seed(42)
regions = ['North', 'South', 'East', 'West']
years = ['2022', '2023']

data_2022 = [np.random.normal(loc, 1, 150) for loc in [5, 4, 6, 5.5]]
data_2023 = [np.random.normal(loc, 1.2, 150) for loc in [6, 5.5, 6.5, 7]]

# Colors
color_2022 = '#6366F1'
color_2023 = '#10B981'

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

positions_2022 = np.array([1, 3, 5, 7]) - 0.4
positions_2023 = np.array([1, 3, 5, 7]) + 0.4

# 2022 violins
vp1 = ax.violinplot(data_2022, positions=positions_2022, widths=0.7,
                    showmeans=True, showmedians=False, showextrema=False)
for body in vp1['bodies']:
    body.set_facecolor(color_2022)
    body.set_edgecolor('white')
    body.set_alpha(0.8)
vp1['cmeans'].set_color('white')
vp1['cmeans'].set_linewidth(2)

# 2023 violins
vp2 = ax.violinplot(data_2023, positions=positions_2023, widths=0.7,
                    showmeans=True, showmedians=False, showextrema=False)
for body in vp2['bodies']:
    body.set_facecolor(color_2023)
    body.set_edgecolor('white')
    body.set_alpha(0.8)
vp2['cmeans'].set_color('white')
vp2['cmeans'].set_linewidth(2)

# Legend
ax.scatter([], [], c=color_2022, s=100, label='2022', marker='s')
ax.scatter([], [], c=color_2023, s=100, label='2023', marker='s')
ax.legend(loc='upper left', frameon=False, fontsize=11)

# Customize axes
ax.set_xticks([1, 3, 5, 7])
ax.set_xticklabels(regions, fontsize=11, fontweight='500')
ax.set_ylabel('Sales Performance', fontsize=12, fontweight='500', color='#374151')
ax.set_xlim(0, 8)

# 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