fundamentos · temario
1.6tema 6 de 13

Visualización de datos

Matplotlib, Seaborn y Plotly para EDA

La visualización de datos es el arte de comunicar información cuantitativa mediante gráficos. Es crítica en Data Science porque el ojo humano detecta patrones en segundos, mientras que leer números en una tabla toma minutos. Las tres librerías principales en Python son: Matplotlib (baja nivel, máxima control, pero verbosa), Seaborn (estadística, bonita por defecto, basada en Matplotlib), y Plotly (interactiva, web-native, excelente para reportes).

Matplotlib es la base de todo. `plt.plot()`, `plt.scatter()`, `plt.hist()`, `plt.bar()` generan gráficos. La API es verbose (hay que especificar figura, ejes, labels, leyenda) pero permite control pixel-perfect. Ejemplo: `plt.figure(figsize=(10, 6))` crea lienzo, `plt.plot(x, y)` dibuja línea, `plt.xlabel()`, `plt.ylabel()`, `plt.title()` etiquetan, `plt.legend()` agrega leyenda, `plt.show()` muestra. Matplotlib guarda como PNG, PDF, SVG.

Seaborn es una capa sobre Matplotlib que automates decisiones estéticas y agrega funcionalidad estadística. `sns.scatterplot(data=df, x='age', y='salary', hue='dept')` colorea por departamento automáticamente. `sns.boxplot()` para distribuciones, `sns.heatmap()` para matrices de correlación, `sns.lineplot()` para series temporales, `sns.histplot()` para distribuciones. Seaborn es mucho más concisa y la salida se ve profesional sin esfuerzo.

Plotly es interactivo y web-native: puedes hacer zoom, hover para ver valores, desseleccionar series con un click. `go.Figure()` es la API baja nivel, `px.scatter()` es la API alto nivel (similar a Seaborn). Plotly genera HTML que puedes compartir o embedder en dashboards. Para reportes y presentations, Plotly es superior porque permite exploración interactiva. Es también la base de Dash (dashboards en Python).

La Exploratory Data Analysis (EDA) es la fase crítica donde visualizas para entender qué hay en los datos. Primero: distribuciones univariadas (histogramas, boxplots de cada columna). Segundo: relaciones bivariadas (scatter de dos variables, correlación). Tercero: multivariante (heatmaps de correlación, pair plots). Las herramientas de EDA rápido (pandas `df.describe()`, `df.corr()`, Seaborn `pairplot()`) son tus amigas. No intentes modelos hasta que entiendas los datos.

Las buenas prácticas en visualización: (1) elige el tipo de gráfico correcto (scatter para relación, bar para categorías, line para series temporal), (2) etiqueta ejes claramente, (3) usa colores deliberadamente (hue para categoría, saturation para magnitud), (4) no uses demasiados colores (confunde), (5) incluye título y legend, (6) considera colorblind-friendly paletas (ej. `palette='husl'` en Seaborn), (7) si comparas magnitudes, usa scale consistente.

structure.txt
# === MATPLOTLIB (low-level, full control) ===
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y, label='sin(x)', color='blue', linewidth=2)
ax.scatter(x[::5], y[::5], color='red', s=50, label='samples')
ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.set_title('Sine Function', fontsize=14)
ax.legend()
ax.grid(True)
plt.tight_layout()
plt.savefig('plot.png', dpi=300)
plt.show()

# === SEABORN (high-level, statistical) ===
import seaborn as sns
import pandas as pd

df = pd.DataFrame({
    'age': [25, 30, 35, 40, 45, 50],
    'salary': [50, 60, 70, 80, 90, 100],
    'dept': ['sales', 'eng', 'eng', 'sales', 'hr', 'eng']
})

# scatter with hue (color by category)
sns.scatterplot(data=df, x='age', y='salary', hue='dept', s=100)
plt.title('Salary vs Age by Department')
plt.show()

# distributions per category
sns.boxplot(data=df, x='dept', y='salary')
plt.show()

# correlation heatmap
sns.heatmap(df.corr(numeric_only=True), annot=True, cmap='coolwarm')
plt.show()

# === PLOTLY (interactive, web-native) ===
import plotly.express as px
import plotly.graph_objects as go

# high-level API
fig = px.scatter(df, x='age', y='salary', color='dept', title='Salary vs Age')
fig.show()  # opens in browser, interactive

# low-level API with more control
fig = go.Figure()
for dept in df['dept'].unique():
    dept_df = df[df['dept'] == dept]
    fig.add_trace(go.Scatter(x=dept_df['age'], y=dept_df['salary'],
                             mode='markers', name=dept))
fig.update_layout(title='Salary vs Age', xaxis_title='Age', yaxis_title='Salary')
fig.show()

Katas (5)

Debugging lab

Detecta y corrige el error en el código.

0/6 tests passing0%
  1. 1.6.5.1

    # Quick histogram of salary distribution df = pd.DataFrame({'salary': [50000, 60000, 55000, 90000, 85000, ...]}) # One outlier makes plot unreadable plt.hist(df['salary'], bins=20) plt.show() # skewed because of one 500k salary

  2. 1.6.5.2

    # Compare salary distributions across departments df = pd.DataFrame({ 'dept': ['sales', 'eng', 'sales', 'eng', ...], 'salary': [50000, 80000, 60000, 75000, ...] }) # Bad: many overlapping distributions for dept in df['dept'].unique(): plt.hist(df[df['dept'] == dept]['salary'], label=dept, alpha=0.5) plt.legend()

  3. 1.6.5.3

    # Heatmap of correlation, but values are tiny and hard to read import seaborn as sns corr = df.corr(numeric_only=True) sns.heatmap(corr, cmap='RdBu') plt.show() # correlation values not visible

  4. 1.6.5.4

    # Scatter with too many points, all overlap plt.scatter(df['age'], df['salary']) plt.show() # overplotting, can't see density

  5. 1.6.5.5

    # Compare two groups: before/after treatment df = pd.DataFrame({ 'group': ['control', 'treatment'] * 50, 'value': [10, 15, 12, 18, ...] }) # Not clear: just overlapping histograms for g in df['group'].unique(): plt.hist(df[df['group'] == g]['value'], alpha=0.5, label=g) plt.legend() plt.show()

  6. 1.6.5.6

    # Interactive dashboard: need to share results with non-technical stakeholder # Matplotlib is static, can't zoom or hover for details