CORRECTION TP 2_VISUALISATION
import pandas as pd
import numpy as np
import [Link] as plt
# ==========================================
# 1. CHARGEMENT DES DONNÉES
# ==========================================
# --- Dataset 1 : Ventes ---
data_ventes = {
'Date': pd.to_datetime(['2025-01-01', '2025-01-02', '2025-01-03', '2025-01-04', '2025-01-05',
'2025-01-06', '2025-01-07', '2025-01-08', '2025-01-09', '2025-01-10',
'2025-01-01', '2025-01-02', '2025-01-03', '2025-01-04', '2025-01-05']),
'Ville': ['Agadir', 'Casablanca', 'Tanger', 'Marrakech', 'Agadir',
'Casablanca', 'Tanger', 'Marrakech', 'Agadir', 'Casablanca',
'Marrakech', 'Agadir', 'Casablanca', 'Tanger', 'Marrakech'],
'Categorie': ['Électronique', 'Vêtements', 'Électronique', 'Meubles', 'Vêtements',
'Électronique', 'Vêtements', 'Meubles', 'Électronique', 'Vêtements',
'Meubles', 'Électronique', 'Vêtements', 'Électronique', 'Meubles'],
'Montant': [12000, 450, 3400, 8000, 300, 15000, 600, 7200, 2500, 500,
9000, 4000, 700, 3200, 5500],
'Age_Client': [22, 45, 34, 58, 19, 36, 25, 62, 28, 41, 55, 23, 33, 29, 60],
'Genre': ['H', 'F', 'H', 'F', 'F', 'H', 'F', 'H', 'H', 'F', 'F', 'H', 'F', 'H', 'F']
}
df = [Link](data_ventes)
# --- Dataset 2 : Performance RH ---
data_perf = {
'Metrique': ['Vitesse', 'Précision', 'Satisfaction Client', 'Assiduité', 'Innovation'],
'Employe_A': [4, 5, 3, 5, 2],
'Employe_B': [3, 4, 5, 4, 5]
}
df_perf = [Link](data_perf)
print("--- Données Chargées ---")
# ==========================================
# 2. PARTIE A : DATA ENGINEERING (TRANSFORMATION)
# ==========================================
# 1. Logique Métier (Apply)
def calcul_commission(montant):
if montant > 10000:
return 500
elif 5000 <= montant <= 10000:
return 200
else:
return 50
df['Commission'] = df['Montant'].apply(calcul_commission)
# 2. Discrétisation (Cut)
bins = [0, 30, 50, 100]
labels = ['Jeune', 'Adulte', 'Senior']
df['Segment_Age'] = [Link](df['Age_Client'], bins=bins, labels=labels)
print(df[['Montant', 'Commission']].head(10))
print(df[['Age_Client', 'Segment_Age']].head(10))
# 3. Agrégation (GroupBy)
df_agg = [Link]('Ville')['Montant'].agg(['sum', 'mean']).reset_index()
print("\n--- Performance par Ville ---")
print(df_agg)
# 4. Tableau Croisé (Pivot Table)
df_pivot = df.pivot_table(index='Ville', columns='Categorie', values='Montant', aggfunc='sum',
fill_value=0)
print("\n--- Pivot Table (Ville x Categorie) ---")
print(df_pivot)
# ==========================================
# 3. PARTIE B : VISUALISATION (REPORTING)
# ==========================================
# Configuration globale pour la lisibilité
[Link]('ggplot')
# --- AXE 1 : ANALYSE TEMPORELLE ---
# 1. Line Plot (Tendance)
df_date = [Link]('Date')['Montant'].sum().reset_index()
[Link](figsize=(10, 5))
[Link](df_date['Date'], df_date['Montant'], marker='o', linestyle='-', color='blue')
[Link]("Évolution du Chiffre d'Affaires")
[Link]("Date")
[Link]("Montant (DH)")
[Link](True)
[Link]()
# 2. Area Plot (Volume)
[Link](figsize=(10, 5))
plt.fill_between(df_date['Date'], df_date['Montant'], color='skyblue', alpha=0.4)
[Link](df_date['Date'], df_date['Montant'], color='Slateblue', alpha=0.6)
[Link]("Volume Cumulé des Ventes")
[Link]()
# 3. Histogramme (Distribution)
[Link](figsize=(8, 5))
[Link](df['Montant'], bins=5, color='orange', edgecolor='black')
[Link]("Distribution des Montants de Transaction")
[Link]("Montant (DH)")
[Link]("Fréquence")
[Link]()
# --- AXE 2 : COMPARAISONS ---
# 4. Bar Chart (Catégorie)
df_cat = [Link]('Categorie')['Montant'].sum()
[Link](figsize=(8, 5))
[Link](df_cat.index, df_cat.values, color=['#1f77b4', '#ff7f0e', '#2ca02c'])
[Link]("CA Total par Catégorie")
[Link]()
# 5. Scatter Plot (Age vs Montant)
[Link](figsize=(8, 5))
[Link](df['Age_Client'], df['Montant'], c='purple', alpha=0.6, s=100)
[Link]("Corrélation : Âge vs Montant")
[Link]("Âge")
[Link]("Montant Acheté")
[Link]()
# 6. Pie Chart (Segments)
counts_age = df['Segment_Age'].value_counts()
[Link](figsize=(6, 6))
[Link](counts_age, labels=counts_age.index, autopct='%1.1f%%', startangle=140, colors=['gold',
'lightgreen', 'lightcoral'])
[Link]("Répartition des Ventes par Segment d'Âge")
[Link]()
# --- AXE 3 : AVANCÉ ---
# 7. Stacked Bar Chart (Ville x Genre)
# Préparation des données pour l'empilement
cross_tab = [Link](df['Ville'], df['Genre'])
cross_tab.plot(kind='bar', stacked=True, color=['#e74c3c', '#3498db'], figsize=(8, 6))
[Link]("Répartition H/F par Ville")
[Link]("Nombre de transactions")
[Link](rotation=45)
[Link]()
# 8. Radar Plot (Performance RH)
# Préparation des angles
labels = df_perf['Metrique']
num_vars = len(labels)
angles = [Link](0, 2 * [Link], num_vars, endpoint=False).tolist()
# Fermer le tracé (boucle)
angles += [angles[0]]
val_a = df_perf['Employe_A'].tolist() + [df_perf['Employe_A'].tolist()[0]]
val_b = df_perf['Employe_B'].tolist() + [df_perf['Employe_B'].tolist()[0]]
[Link](figsize=(6, 6))
ax = [Link](polar=True)
# Tracé Employé A
[Link](angles, val_a, linewidth=1, linestyle='solid', label='Employé A')
[Link](angles, val_a, 'b', alpha=0.1)
# Tracé Employé B
[Link](angles, val_b, linewidth=1, linestyle='solid', label='Employé B')
[Link](angles, val_b, 'r', alpha=0.1)
# Labels
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
[Link]("Comparaison des Compétences")
[Link](loc='upper right', bbox_to_anchor=(1.1, 1.1))
[Link]()