12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
np.random.seed(42)
n = 500
hr = pd.DataFrame({
'Dept': np.random.choice(['Engineering','Marketing','Sales','HR','Finance'], n, p=[0.35,0.2,0.25,0.1,0.1]),
'Gender': np.random.choice(['Male','Female'], n, p=[0.55,0.45]),
'Salary': np.random.normal(75000, 20000, n).clip(30000, 200000),
'Performance': np.random.choice([1,2,3,4,5], n, p=[0.05,0.15,0.35,0.30,0.15]),
'Tenure': np.random.randint(1, 20, n),
'Satisfaction':np.random.uniform(1, 10, n).round(1),
'Left': np.random.choice([0,1], n, p=[0.8,0.2])
})
sns.set_theme(style='whitegrid')
fig, axes = plt.subplots(2, 3, figsize=(16, 10))
sns.violinplot(data=hr, x='Dept', y='Salary', ax=axes[0,0], palette='Blues')
axes[0,0].set_title('Salary Distribution by Department')
axes[0,0].set_xticklabels(axes[0,0].get_xticklabels(), rotation=20)
sns.boxplot(data=hr, x='Dept', y='Performance', hue='Gender', ax=axes[0,1], palette='Set2')
axes[0,1].set_title('Performance by Department & Gender')
axes[0,1].set_xticklabels(axes[0,1].get_xticklabels(), rotation=20)
# Attrition by department
attr = hr.groupby('Dept')['Left'].mean() * 100
attr.sort_values().plot(kind='barh', ax=axes[0,2], color='#F44336', alpha=0.8)
axes[0,2].set_title('Attrition Rate by Department (%)')
axes[0,2].set_xlabel('%')
sns.scatterplot(data=hr, x='Satisfaction', y='Performance', hue='Left',
palette={0: '#4CAF50', 1: '#F44336'}, alpha=0.5, ax=axes[1,0])
axes[1,0].set_title('Satisfaction vs Performance\n(Red=Left, Green=Stayed)')
# Heatmap: dept × metric
pivot = hr.groupby('Dept')[['Salary','Performance','Satisfaction','Tenure']].mean()
pivot_norm = (pivot - pivot.min()) / (pivot.max() - pivot.min())
sns.heatmap(pivot_norm, annot=True, fmt='.2f', cmap='RdYlGn', ax=axes[1,1])
axes[1,1].set_title('Normalized HR Metrics Heatmap')
sns.kdeplot(data=hr, x='Salary', hue='Dept', fill=True, alpha=0.3, ax=axes[1,2])
axes[1,2].set_title('Salary Distribution by Department')
axes[1,2].xaxis.set_major_formatter(plt.FuncFormatter(lambda x,_: f'${x/1000:.0f}K'))
plt.suptitle('HR Analytics Dashboard', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.savefig('hr_dashboard.png', dpi=150, bbox_inches='tight')
plt.show()