Streamlit usage¶
To use idendrogram in Streamlit, make sure you have installed the accompanying package idendrogram-streamlit-component
. If you have not installed it together with idendrogram, get it:
pip install idendrogram_streamlit_component
The usage is identical to any other visualization backend. The key difference is that to_streamlit()
function returns ClusterNode
object if the user clicks on any of the nodes in the dendrogram. This allows creating interactive experiences where the user can get more information about a particular (sub/super) cluster in a dendrogram.
import idendrogram
import scipy.cluster.hierarchy as sch
from idendrogram.targets.streamlit import to_streamlit
#cluster the data
linkage_matrix = sch.linkage(
data['data'], method='single', metric='euclidean'
)
threshold = 0.8
flat_clusters = sch.fcluster(
linkage_matrix, t=threshold, criterion='distance'
)
#wrap clustering outputs / parameters into a container
cl_data = idendrogram.ClusteringData(
linkage_matrix = linkage_matrix,
cluster_assignments = flat_clusters
)
#pass to idendrogram and create a dendrogram object
idd = idendrogram.idendrogram()
idd.set_cluster_info(cl_data)
dendrogram = idd.create_dendrogram(truncate_mode='level', p=10)
#visualize in streamlit and get the data object behind the selected node
#selected_node = to_streamlit(dendrogram=dendrogram, height=200, width=629)
Customizing Streamlit dendrograms¶
Developers familiar with D3 may want to customize the dendrogram component further (e.g. create richer tooltips). The source of the streamlit component with some guidance on its structure is available at https://github.com/kamicollo/idendrogram-streamlit.
Assuming you have the node.js
server running locally that's serving the Streamlit component, you can get the idendrogram_streamlit_component
to point to the local version as follows:
from idendrogram_streamlit_component import StreamlitConverter
#set release flag to False
converter = StreamlitConverter(release=False)
#pass to idendrogram and create a dendrogram object
idd = idendrogram.idendrogram()
idd.set_cluster_info(cl_data)
dendrogram = idd.create_dendrogram(truncate_mode='level', p=10)
#render in Streamlit
converter.convert(
dendrogram,
height=500,
width=500,
scale='linear',
key='idendrogram',
orientation = 'top',
show_nodes = True,
margins = {'top': 50, 'bottom': 50, 'left': 50, 'right': 50}
)
Adjusting Streamlit dendrogram margins¶
The same method as above can be used to pass custom margins to be used to render the dendrogram. Just do not set release=False
, but use the StreamlitConverter
to pass custom margins instead.