Hi! I’m using a Treemap in a Vizro dashboard built with Dash/Plotly.
Because my data has different hierarchy depths, I built the treemap manually using ids , parents , and labels .
Here is the code I use to generate the treemap:
def mapa_arbol_plata(data_frame):
# 2. Diccionarios para acumular los nodos únicos
# Usamos diccionarios para sumar los valores de 'Ventas' cuando los niveles se repiten
ids_dict = {}
labels_dict = {}
parents_dict = {}
# Niveles jerárquicos
niveles = ["Nivel1", "Nivel2", "Nivel3", "Nivel4"]
# 3. Procesar el DataFrame fila por fila
for _, row in data_frame.iterrows():
parent_id = "" # El nivel raíz no tiene padre
for i, nivel in enumerate(niveles):
current_val = row[nivel]
# Si el nivel es nulo o vacío, dejamos de procesar esta fila
if pd.isna(current_val) or current_val == "":
break
# Construimos un ID único combinando el camino para evitar colisiones de nombres iguales
if i == 0:
current_id = str(current_val)
else:
current_id = f"{parent_id} / {current_val}"
# Si el ID ya existe, sumamos el valor; si no, lo creamos
if current_id in ids_dict:
ids_dict[current_id] += 1
else:
ids_dict[current_id] = 1
labels_dict[current_id] = str(current_val)
parents_dict[current_id] = parent_id
# El ID actual se convierte en el padre del siguiente nivel
parent_id = current_id
# 4. Extraer las listas finales para Plotly
plot_ids = list(ids_dict.keys())
plot_labels = list(labels_dict.values())
plot_parents = list(parents_dict.values())
plot_values = list(ids_dict.values())
# 5. Generar el gráfico Treemap
fig = go.Figure(go.Treemap(
ids=plot_ids,
labels=plot_labels,
parents=plot_parents,
values=plot_values,
branchvalues="total", # Suma correctamente los valores de los hijos en los padres
customdata=plot_ids, # Para mostrar el valor en el hover
))
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
What I would like to do is:
- Click/select a box in the treemap
- Use that selection to filter an AG Grid table in the dashboard
I’m not sure what is the best way to achieve this in Dash/Vizro.
Any example or recommendation would be very helpful.
Thanks!