Interactive hierarchical clustering

Hi,

I want to display an interactive dendrogram (a tree representing the result of the an hierarchical clustering), such that when i put the cursor over a node – either a leaf of an inner node – I can see some labels corresponding to leaves within the subtree rooted in the node.

What I currently have:

import time
import numpy as np
import streamlit as st
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use(β€˜TkAgg’)

progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()

import time
import numpy as np
import streamlit as st
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use(β€˜TkAgg’)
random.seed(0)
np.random.seed(0)
progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()

from scipy.cluster.hierarchy import linkage, dendrogram
from matplotlib import pyplot as plt
data = np.random.rand(1000,30) - 0.5
labels = [β€œa”, β€œb”, β€œc”, β€œd”, β€œe”, β€œf”," ,β€œg”, β€œh”, β€œi”, β€œj”]
Z = linkage(data, optimal_ordering = False, method = β€˜ward’)
dn = dendrogram(Z, truncate_mode = β€˜lastp’)
st.pyplot()
print(β€œHere”)
progress_bar.empty()

Streamlit widgets automatically run the script from top to bottom. Since

this button is not connected to any other logic, it just causes a plain

rerun.

st.button(β€œRe-run”)

I want to be able to put the cursor over the leaf corresponding to the label "a", and see that label; or put the cursor over the inner node which is the ancestor of the leaves "a", "e", "h" and "j", and see those labels (see image).


Thanks!

Hey,

I’m not sure it’s easy to do interactive charting with Matplotlib, but Streamlit can also display plotly which has an interactive tree-plot. It’s the only interactive tree I could find within the supported interactive plotting options for Streamlit.

That would need figuring out how to transpose the dendogram leaves output into plotly input though, maybe that could be a good strarting point.

Hi @Shauli_Ravfogel,
definitely you can try out other plotting libraries that are offered in Streamlit. I think altair and bokeh also support interactive chart, but you will have to transpose your model as suggested by @andfanilo.

Best,
Matteo