🎯 Objectifs de la séance

1. Principes de Data Visualisation

📖 Qu'est-ce qu'une bonne visualisation ?

  • Claire : Message évident au premier regard
  • Précise : Représente fidèlement les données
  • Pertinente : Adapté au type de données et au message
  • Esthétique : Agréable visuellement
  • Accessible : Compréhensible par tous

🎯 Choisir le bon type de graphique

Objectif Type de graphique Usage
Comparer des catégories Barres Ventes par produit
Montrer une évolution Lignes CA mensuel
Voir une relation Scatter Prix vs quantité
Partie du tout Pie chart % par catégorie
Comparer distributions Boxplot Salaires par département

❌ Erreurs courantes à éviter

  • Graphique 3D inutile (difficile à lire)
  • Trop de couleurs (confusion visuelle)
  • Échelles trompeuses (manipulation)
  • Graphique surchargé (trop d'infos)
  • Mauvais type de graphique

2. Plotly pour l'Interactivité

🖱️ Pourquoi Plotly ?

Plotly crée des graphiques interactifs : zoom, hover, pan, légendes cliquables.

import plotly.express as px

# Scatter interactif
fig = px.scatter(df, x="total_bill", y="tip", color="day",
                 hover_data=["size"], title="Tips Dataset")
fig.show()

# Line chart
fig = px.line(df_time, x="date", y="value", 
              title="Évolution temporelle")
fig.show()

# Bar chart
fig = px.bar(df_cat, x="categorie", y="ventes", color="region")
fig.show()

# Pie chart
fig = px.pie(df_cat, values="ventes", names="categorie")
fig.show()

📊 Graphiques avancés

# Graphique à bulles
fig = px.scatter(df, x="prix", y="quantite", size="ca", 
                 color="categorie", hover_name="produit")

# Sunburst (hiérarchique)
fig = px.sunburst(df, path=["region", "ville", "magasin"], 
                  values="ventes")

# Treemap
fig = px.treemap(df, path=["categorie", "produit"], 
                 values="ventes", color="marge")

3. Introduction à Streamlit

🚀 Qu'est-ce que Streamlit ?

Streamlit est un framework Python pour créer des applications web data sans JavaScript/HTML/CSS.

Avantages :

  • ✅ 100% Python
  • ✅ Très rapide à développer
  • ✅ Réactif et interactif
  • ✅ Déploiement gratuit
  • ✅ Intégration facile avec Pandas, Plotly, etc.

🎯 Premier script Streamlit

# app.py
import streamlit as st

st.title("Mon premier dashboard 📊")
st.write("Hello World!")

# Slider
age = st.slider("Votre âge", 0, 100, 25)
st.write(f"Vous avez {age} ans")

# Checkbox
if st.checkbox("Afficher les données"):
    st.write({"a": 1, "b": 2})

# Bouton
if st.button("Cliquez ici"):
    st.balloons()

Lancer l'application :

streamlit run app.py

4. Layout et Organisation

import streamlit as st

# Page config (doit être en premier)
st.set_page_config(
    page_title="Mon Dashboard",
    page_icon="📊",
    layout="wide"
)

# Sidebar
st.sidebar.title("Navigation")
page = st.sidebar.radio("Aller à", ["Accueil", "Analyse", "Visualisation"])

# Colonnes
col1, col2, col3 = st.columns(3)
with col1:
    st.metric("CA", "150K €", "+12%")
with col2:
    st.metric("Clients", "1.2K", "+5%")
with col3:
    st.metric("Panier moyen", "125 €", "-2%")

# Tabs
tab1, tab2, tab3 = st.tabs(["Données", "Graphiques", "Stats"])

with tab1:
    st.write("Contenu tab 1")

with tab2:
    st.write("Contenu tab 2")

5. Widgets Interactifs

# Input text
nom = st.text_input("Nom")

# Number input
quantite = st.number_input("Quantité", min_value=1, max_value=100)

# Slider
prix_max = st.slider("Prix maximum", 0, 1000, 500)

# Select box
categorie = st.selectbox("Catégorie", ["A", "B", "C"])

# Multi select
produits = st.multiselect("Produits", 
                          ["Laptop", "Souris", "Clavier"])

# Date input
date = st.date_input("Date")

# File uploader
fichier = st.file_uploader("Choisir un fichier CSV")
if fichier:
    df = pd.read_csv(fichier)
    st.write(df)

6. Connexion Streamlit ↔ DuckDB

🔗 Application complète

import streamlit as st
import duckdb
import pandas as pd
import plotly.express as px

st.set_page_config(page_title="Dashboard Ventes", layout="wide")

# Connexion DuckDB
@st.cache_resource
def get_connection():
    return duckdb.connect("data/sales.db")

con = get_connection()

# Sidebar - Filtres
st.sidebar.title("Filtres")
date_debut = st.sidebar.date_input("Date début")
date_fin = st.sidebar.date_input("Date fin")

# Requête avec filtres
@st.cache_data
def load_data(date_debut, date_fin):
    query = f"""
        SELECT *
        FROM ventes
        WHERE date BETWEEN "{date_debut}" AND "{date_fin}"
    """
    return con.execute(query).fetchdf()

df = load_data(date_debut, date_fin)

# KPIs
col1, col2, col3 = st.columns(3)
col1.metric("CA Total", f"{df["montant"].sum():,.0f} €")
col2.metric("Nb Ventes", len(df))
col3.metric("Panier Moyen", f"{df["montant"].mean():,.0f} €")

# Graphiques
fig = px.bar(df.groupby("categorie")["montant"].sum().reset_index(),
             x="categorie", y="montant")
st.plotly_chart(fig, use_container_width=True)

⚡ Caching pour la performance

@st.cache_data : Cache les données

@st.cache_resource : Cache les connexions

🎯 Quiz de validation des connaissances

Testez vos connaissances sur Streamlit et la visualisation ! 10 questions.

🎓 Points clés à retenir

📚 Ressources complémentaires