2
$\begingroup$

The chapter "Normalized Information Distance", visualizes a hierarchical clustering as a tree of nodes with labels: Hierarchical Clustering visualization from "Normalized Information Distance"

Unfortunately I cannot find out how to replicate this visualization, maybe they did it in a manual way with Tikz? How can I achieve this effect automatically in Python, preferably with Scikit-Learn? I only found the Dendogram, which looks nothing like the effect I want to replicate:

enter image description here

Result (thanks at @andy-w):

model = AgglomerativeClustering(linkage="average", n_clusters=N_CLUSTERS, compute_distances=True, affinity="l1")
model.fit(data)
no_of_observations = np.arange(2, model.children_.shape[0]+2)
linkage_matrix = np.column_stack([model.children_, model.distances_, no_of_observations]).astype(float)

G = nx.Graph()    
n = len(linkage_matrix)
for i in range(n):
    row = linkage_matrix[i]
    G.add_edge(label(int(row[0])),label(n+i+1),len=1+0.1*(math.log(1+row[2])))  
    G.add_edge(label(int(row[1])),label(n+i+1),len=1+0.1*(math.log(1+row[2])))  

dot = nx.nx_pydot.to_pydot(G).to_string()
dot = graphviz.Source(dot, engine='neato')
dot.render(format='pdf',filename='tree')

result so far

$\endgroup$

1 Answer 1

3
+50
$\begingroup$

This specific format to me looks like graphviz. So if you can extract the tree edges from your original object, then you can render it, example below (some roundabout to convert between different objects):

import networkx as nx
import pydot
import graphviz

# Just a part of your graph
G = nx.Graph()
ed = [('n3','n0'),
      ('n0','MusicHendrixA'),
      ('n0','MusicHendrixB'),
      ('n3','n2'),
      ('n2','n8'),
      ('n8','MusicBergA'),
      ('n8','MusicBergB') ]
G.add_edges_from(ed)

# Now the graphviz part
dot = nx.nx_pydot.to_pydot(G).to_string()
dot = graphviz.Source(dot, engine='neato')
dot.render(format='png',filename='MusicTree')

GraphViz Output Neato

$\endgroup$
2
  • $\begingroup$ The part on how to draw a graph is very helpful, however my main problem is the conversion itself. However I got some pointers in that direction at stackoverflow.com/questions/9838861/scipy-linkage-format. $\endgroup$ Commented Sep 15, 2021 at 10:46
  • $\begingroup$ Nice job @KonradHöffner! (Agree when I looked at the internals figuring out the nodes/edges was not straightforward.) $\endgroup$
    – Andy W
    Commented Sep 15, 2021 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.