Vai al contenuto
__HTML_TAG_110_📄 Generare Seaborn PDF Guide_HTML_TAG_111__

Seaborn Cheatsheet

Installazione

Tabella_114_

Comandi di base

Tabella_115

Uso avanzato

Tabella_116_

Configurazione

Configurazione tema e stile

# Comprehensive theme setup
sns.set_theme(
    style="darkgrid",           # whitegrid, darkgrid, white, dark, ticks
    palette="deep",             # Color palette
    font="sans-serif",          # Font family
    font_scale=1.2,             # Scale all fonts
    color_codes=True,           # Use color codes
    rc={                        # Matplotlib rcParams
        "figure.figsize": (12, 8),
        "axes.labelsize": 14,
        "axes.titlesize": 16,
        "xtick.labelsize": 12,
        "ytick.labelsize": 12,
        "legend.fontsize": 12
    }
)

Scala basata sul testo

# Scale plots for different contexts
sns.set_context(
    "talk",                     # paper, notebook, talk, poster
    font_scale=1.5,
    rc={"lines.linewidth": 2.5}
)

Palette di colore personalizzate

# Define custom color palette
custom_colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#FFA07A", "#98D8C8"]
sns.set_palette(sns.color_palette(custom_colors))

# Or use built-in palettes
sns.set_palette("Set2", n_colors=8)

Temporary Style Context

# Apply style temporarily
with sns.axes_style("white"):
    sns.boxplot(data=df, x='category', y='value')
    plt.show()
# Original style restored after block

Parametri funzione figura-scivolo

# Common parameters for figure-level functions
g = sns.relplot(
    data=df,
    x='x', y='y',
    hue='category',
    col='group',
    col_wrap=3,              # Wrap columns after 3
    height=4,                # Height of each facet
    aspect=1.5,              # Aspect ratio (width = height * aspect)
    palette='viridis',
    legend='full'            # 'auto', 'brief', 'full', False
)

Common Use Cases

Use Case 1: Exploratory Analisi dei dati

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# Load data
df = pd.read_csv('data.csv')

# Quick overview with pairplot
sns.pairplot(df, hue='target_variable', diag_kind='kde')
plt.savefig('pairplot.png', dpi=300, bbox_inches='tight')

# Correlation heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(df.corr(), annot=True, fmt='.2f', cmap='coolwarm', center=0)
plt.title('Feature Correlation Matrix')
plt.tight_layout()
plt.savefig('correlation.png', dpi=300)

Use Case 2: Confronto di distribuzione

# Compare distributions across categories
fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# Histogram with KDE
sns.histplot(data=df, x='value', hue='category', kde=True, ax=axes[0, 0])
axes[0, 0].set_title('Distribution with KDE')

# Violin plot
sns.violinplot(data=df, x='category', y='value', ax=axes[0, 1])
axes[0, 1].set_title('Violin Plot')

# Box plot with swarm overlay
sns.boxplot(data=df, x='category', y='value', ax=axes[1, 0])
sns.swarmplot(data=df, x='category', y='value', color='black', alpha=0.3, ax=axes[1, 0])
axes[1, 0].set_title('Box + Swarm Plot')

# ECDF
sns.ecdfplot(data=df, x='value', hue='category', ax=axes[1, 1])
axes[1, 1].set_title('Cumulative Distribution')

plt.tight_layout()
plt.show()

Use Case 3: Time Series Visualization

# Time series with confidence intervals
df['date'] = pd.to_datetime(df['date'])

# Line plot with shaded confidence interval
plt.figure(figsize=(14, 6))
sns.lineplot(
    data=df,
    x='date',
    y='value',
    hue='category',
    style='category',
    markers=True,
    dashes=False,
    ci=95,
    err_style='band'
)
plt.xticks(rotation=45)
plt.title('Time Series with 95% Confidence Intervals')
plt.tight_layout()
plt.show()

Use Case 4: Multi-Variable Faceted Analysis

# Create faceted plot for complex relationships
g = sns.FacetGrid(
    df,
    col='region',
    row='product_type',
    hue='customer_segment',
    height=4,
    aspect=1.2,
    margin_titles=True
)

g.map_dataframe(sns.scatterplot, x='price', y='sales', alpha=0.6)
g.add_legend(title='Customer Segment')
g.set_axis_labels('Price ($)', 'Sales Volume')
g.set_titles(col_template="{col_name}", row_template="{row_name}")
g.tight_layout()
plt.savefig('faceted_analysis.png', dpi=300, bbox_inches='tight')

Use Case 5: Analisi della regressione statistica

# Multiple regression visualizations
fig, axes = plt.subplots(1, 3, figsize=(18, 5))

# Linear regression
sns.regplot(data=df, x='feature1', y='target', ax=axes[0])
axes[0].set_title('Linear Regression')

# Polynomial regression
sns.regplot(data=df, x='feature2', y='target', order=3, ax=axes[1])
axes[1].set_title('Polynomial Regression (Order 3)')

# Residual plot
sns.residplot(data=df, x='feature1', y='target', ax=axes[2])
axes[2].set_title('Residual Plot')
axes[2].axhline(0, ls='--', color='red', alpha=0.5)

plt.tight_layout()
plt.show()

Migliori Pratiche

  • Utilizza funzioni a livello di figura per il faceting: Funzioni come relplot(), catplot(), e lmplot()___ gestire automaticamente la creazione di figure e assi, rendendo i grafici sfaccettati più facili da gestire

  • Scegli i tipi di appezzamento appropriati Utilizzare appezzamenti di violino per il confronto di distribuzione, appezzamenti di scatole per il rilevamento di outlier, appezzamenti di sciame per piccoli set di dati, e appezzamenti di strisce per set di dati di medie dimensioni

  • Leverage il parametro data: Utilizzare sempre il parametro data__ con pandas DataFrames per un codice più pulito e una migliore integrazione con i flussi di lavoro di manipolazione dei dati

  • Si'. Chiama sns.set_theme() o sns.set_style() all'inizio del tuo script per garantire uno styling coerente su tutti i grafici

  • Usa mappature semantiche: Approfitta dei parametri hue, size, e style__ per codificare dimensioni aggiuntive nelle tue visualizzazioni senza creare grafici separati

  • Risparmiare cifre ad alta risoluzione. Utilizzare plt.savefig('file.png', dpi=300, bbox_inches='tight') per immagini di qualità della pubblicazione con margini adeguati

  • Combine Seaborn con Matplotlib**: Utilizzare Seaborn per grafici statistici rapidi e Matplotlib per la personalizzazione fine-tuned (titolo, etichette, annotazioni, ecc.)

  • I grandi set di dati in modo efficiente: Per i set di dati con >10,000 punti, prendere in considerazione l'utilizzo rasterized=True_ in appezzamenti di spargimento o aggregare i dati prima di tracciare

  • ** Utilizzare palette di colori strategicamente**: Scelga palette sequenziali per i dati ordinati, tavolozze divergenti per i dati con un centro significativo, e palette qualitative per i dati categorici

  • Ricorda le tue scelte di colore # Quando si creano visualizzazioni per il pubblico di colorblind, utilizzare tavolozze colorblind-friendly come __INLINE_CODE_73_ o testare con sns.color_palette("colorblind")

Risoluzione dei problemi

Issue Solution
Plot not displaying Add INLINE_CODE_75 at the end or use INLINE_CODE_76 in Jupyter notebooks
Legend overlapping plot Use INLINE_CODE_77 or INLINE_CODE_78
Categorical axis labels overlapping Rotate labels with INLINE_CODE_79 or use horizontal plots with INLINE_CODE_80
Heatmap annotations too small Increase figure size INLINE_CODE_81 or adjust font size INLINE_CODE_82
Color palette not applying Set palette before creating plot with INLINE_CODE_83 or use INLINE_CODE_84 parameter directly in plot function
FacetGrid plots too small Increase INLINE_CODE_85 parameter (e.g., INLINE_CODE_86) and adjust INLINE_CODE_87 ratio (e.g., INLINE_CODE_88)
Missing confidence intervals Ensure sufficient data points; CI requires multiple observations per x-value. Use INLINE_CODE_89 to disable
Seaborn overriding Matplotlib settings Reset with INLINE_CODE_90 or INLINE_CODE_91 to restore Matplotlib defaults
Memory issues with large datasets Use INLINE_CODE_92 for scatter plots or downsample data before plotting
KDE plot looks wrong Adjust INLINE_CODE_93 parameter (e.g., INLINE_CODE_94 for narrower bandwidth) or use INLINE_CODE_95 to limit range
Regression line not fitting data Try polynomial regression with INLINE_CODE_96 or INLINE_CODE_97, or use INLINE_CODE_98 for outlier resistance
Heatmap colors not centered Use INLINE_CODE_99 parameter and diverging colormap like INLINE_CODE_100 for data with meaningful zero point
Plot style not persisting Use INLINE_CODE_101 instead of INLINE_CODE_102 (deprecated) or set INLINE_CODE_103 parameters explicitly
Facet titles cut off Add INLINE_CODE_104 or use INLINE_CODE_105 for FacetGrid objects
** Errori di importazione dopo l'installazione** Restart Python kernel/IDE o verifica l'installazione con pip show seaborn e controlla le dipendenze