29  Gráficas interactivas con ipywidgets

Estas herramientas interactivas en HTML nos permiten llevar nuestra exploración de datos al siguiente nivel, todo mientras permanecemos dentro del entorno familiar de Jupyter. Desde simples deslizadores hasta botones y casillas de verificación, ipywidgets nos brinda la capacidad de interactuar en tiempo real con nuestros datos.

Ipywidgets solo funciona en el entorno de Jupyter Notebook, así que ten cuidado si estás usando JupyterLab u otro IDE.

# pip install ipywidgets --upgrade --user
import pandas as pd
import matplotlib.pyplot as plt
from ipywidgets import interact, widgets
def f(x):
    return print(f"el numero es {x}")
interact(f,x=-10)
f = "../data/Cuernavaca_Enero_comas.csv"
cuerna = pd.read_csv(f,index_col=0,parse_dates=True)
cuerna.head()
To RH P Ws Wd Ig Ib Id
tiempo
2012-01-01 00:00:00 19.3 58 87415 0.0 26 0 0 0
2012-01-01 01:00:00 18.6 59 87602 0.0 26 0 0 0
2012-01-01 02:00:00 17.9 61 87788 0.0 30 0 0 0
2012-01-01 03:00:00 17.3 66 87554 0.0 30 0 0 0
2012-01-01 04:00:00 16.6 71 87321 0.0 27 0 0 0
def grafica_serie(start, end):
    # Filtrar la serie temporal por el rango de fechas
    filtrado = cuerna[start:end]
    
    # Graficar la serie temporal filtrada
    fig, ax = plt.subplots(figsize=(10, 5))
    ax.plot(filtrado.To)
    ax.set_xlabel('Fecha')
    ax.set_ylabel('Valor')
    ax.grid()
inicio_picker = widgets.DatePicker(description='Fecha inicio', value=pd.to_datetime('2012-01-01'))
fin_picker    = widgets.DatePicker(description='Fecha fin'   , value=pd.to_datetime('2012-01-31'))
widgets.interact(grafica_serie, start=inicio_picker, end=fin_picker)
<function __main__.grafica_serie(start, end)>