在Networkx中可视化Louvain分区 [英] Visualization of Louvain partitions in Networkx

查看:58
本文介绍了在Networkx中可视化Louvain分区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我更改可视化Louvain聚类算法的结果.我从网站上获取了代码

Please help me change visualize the result of Louvain clustering algorithm. I took the code from the site https://github.com/taynaud/python-louvain Can I rewrite the code so that each cluster has its own shape (circle, triangle, square ...)?

import community as community_louvain
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import networkx as nx

# load the karate club graph
G = nx.karate_club_graph()

# compute the best partition
partition = community_louvain.best_partition(G)

# draw the graph
pos = nx.spring_layout(G)
# color the nodes according to their partition
cmap = cm.get_cmap('viridis', max(partition.values()) + 1)
nx.draw_networkx_nodes(G, pos, partition.keys(), node_size=40,
                       cmap=cmap, node_color=list(partition.values()))
nx.draw_networkx_edges(G, pos, alpha=0.5)
plt.show()

解决方案

Unfortunately nx.draw_networkx_nodes does not accept an iterable of shapes, so you'll have to loop over the nodes and plot them individually. Also, we'll have to index the generated cmap, otherwise, the single valued community values will get mapped to the same initial cmap color. For the possible shapes I'm just replicating the string of available shapes mentioned in the docs and indexing it based on the partition number:

# load the karate club graph
G = nx.karate_club_graph()

# compute the best partition
partition = community_louvain.best_partition(G)

cmap = cm.get_cmap('viridis', max(partition.values()) + 1)
shapes = 'so^>v<dph8'

plt.figure(figsize=(12,8))
# draw the graph
pos = nx.spring_layout(G)
# color the nodes according to their partition
cmap = cm.get_cmap('viridis', max(partition.values()) + 1)
nx.draw_networkx_edges(G, pos, alpha=0.5)
for node, color in partition.items():
    nx.draw_networkx_nodes(G, pos, [node], node_size=100,
                           node_color=[cmap.colors[color]],
                           node_shape=shapes[color])

这篇关于在Networkx中可视化Louvain分区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆