【问题标题】:Drawing a community in networkx, anything I am doing incorrectly?在networkx中绘制社区,我做错了什么?
【发布时间】:2022-10-23 22:03:23
【问题描述】:

试图做这样的事情,但我不确定我做错了什么

import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nxcom

G = nx.karate_club_graph()
greedy = nxcom.greedy_modularity_communities(G) 
#returns a list with type frozen sets within the list
#[{set1},{set2},{set3}]

pos = nx.spring_layout(G)  # compute graph layout
plt.axis('off')
nx.draw_networkx_nodes(G, pos, cmap=plt.cm.RdYlBu, node_color=list(greedy.values()))
plt.show(G)

【问题讨论】:

  • 运行代码时会发生什么?您是否遇到任何错误,或者只是没有在正确的位置绘制内容?你期待看到什么与你实际看到什么?

标签: matplotlib graph networkx graph-theory


【解决方案1】:

看起来您的问题来自您将颜色映射到社区的方式。由于来自nx.draw_networkx_nodesnode_color 参数预计是一个颜色列表(参见文档here),因此您需要将每个节点与其社区关联的颜色相关联。您可以使用以下方法做到这一点:

c=plt.cm.RdYlBu(np.linspace(0,1,len(greedy))) #create a list of colors, one for each community
colors={list(g)[j]:c[i] for i,g in enumerate(greedy) for j in range(len(list(g)))} #for each node associate the node with the color of its community
colors_sort=dict(sorted(colors.items())) #sort the dictionary by keys such

然后,您可以将排序字典的值转换为列表,并将其传递给 nx.draw_networkx_nodesnx.draw_networkx_nodes(G, pos,node_color=list(colors_sort.values()))

请参阅下面的完整代码:

import networkx as nx
import matplotlib.pyplot as plt
import networkx.algorithms.community as nxcom
import numpy as np

G = nx.karate_club_graph()
greedy = nxcom.greedy_modularity_communities(G) 
c=plt.cm.RdYlBu(np.linspace(0,1,len(greedy)))
colors={list(g)[j]:c[i] for i,g in enumerate(greedy) for j in range(len(list(g)))}
colors_sort=dict(sorted(colors.items()))
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos,node_color=list(colors_sort.values()))
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos,labels={n:str(n) for n in G.nodes()})
plt.axis('off')
plt.show(G)

【讨论】:

    猜你喜欢
    • 2017-09-18
    • 2019-12-21
    • 1970-01-01
    • 2023-03-10
    • 2012-07-07
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多