gpt4 book ai didi

python - Networkx 中 Louvain 分区的可视化

转载 作者:行者123 更新时间:2023-12-04 09:29:48 55 4
gpt4 key购买 nike

请帮我更改可视化 Louvain 聚类算法的结果。
我从网站上拿了代码
https://github.com/taynaud/python-louvain
我可以重写代码以便每个集群都有自己的形状(圆形、三角形、方形...)吗?

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()

最佳答案

不幸的是 nx.draw_networkx_nodes 不接受可迭代的形状,因此您必须遍历节点并单独绘制它们。此外,我们必须索引生成的 cmap ,否则,单值社区值将映射到相同的初始 cmap 颜色。对于可能的形状,我只是复制了 docs 中提到的可用形状串。并根据分区号对其进行索引:

# 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])
enter image description here

关于python - Networkx 中 Louvain 分区的可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62890682/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com