From 5146f98f17b400ec96d7dad37d54ce8e03807868 Mon Sep 17 00:00:00 2001 From: Ross Barnowski Date: Tue, 31 Oct 2023 14:57:53 -0700 Subject: [PATCH] Hierarchical clustering layout gallery example (#7058) * Add clustered layout gallery example. * Minor viz tweaks. --- examples/drawing/plot_clusters.py | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 examples/drawing/plot_clusters.py diff --git a/examples/drawing/plot_clusters.py b/examples/drawing/plot_clusters.py new file mode 100644 index 00000000000..d768a3bc7c9 --- /dev/null +++ b/examples/drawing/plot_clusters.py @@ -0,0 +1,36 @@ +""" +============== +Cluster Layout +============== + +This example illustrates how to combine multiple layouts to visualize node +clusters. + +The approach used here can be generalized to visualize hierarchical clustering +e.g. clusters-of-clusters of nodes by combining layouts with varying scale +factors. +""" +import networkx as nx +import matplotlib.pyplot as plt + +G = nx.davis_southern_women_graph() # Example graph +communities = nx.community.greedy_modularity_communities(G) + +# Compute positions for the node clusters as if they were themselves nodes in a +# supergraph using a larger scale factor +supergraph = nx.cycle_graph(len(communities)) +superpos = nx.spring_layout(G, scale=50, seed=429) + +# Use the "supernode" positions as the center of each node cluster +centers = list(superpos.values()) +pos = {} +for center, comm in zip(centers, communities): + pos.update(nx.spring_layout(nx.subgraph(G, comm), center=center, seed=1430)) + +# Nodes colored by cluster +for nodes, clr in zip(communities, ("tab:blue", "tab:orange", "tab:green")): + nx.draw_networkx_nodes(G, pos=pos, nodelist=nodes, node_color=clr, node_size=100) +nx.draw_networkx_edges(G, pos=pos) + +plt.tight_layout() +plt.show()