【问题标题】:How to draw specific communities from networkx while ignoring the other communities?如何从networkx中提取特定社区而忽略其他社区?
【发布时间】:2020-05-07 13:50:48
【问题描述】:

我有一个由 103 个社区组成的网络。社区编号 9 拥有最多的成员,约有 12,000 名成员。我只想画那个,因为整个图有大约 70k 个节点而且它太大了。

largest_subgraph = max(nx.connected_component_subgraphs(graph),key=len)

partition=community.best_partition(largest_subgraph)
values=[partition.get(node) for node in largest_subgraph.nodes()]
list_com=partition.values()

dict_nodes={}

for each_item in partition.items():
    community_num=each_item[1]
    community_node=each_item[0]
    if community_num in dict_nodes:
        value=dict_nodes.get(community_num) + ' | ' + str(community_node)
        dict_nodes.update({community_num:value})
    else:
        dict_nodes.update({community_num:community_node})

plt.rcParams['figure.figsize']= [12, 8]
G_comm=nx.Graph()

G_comm.add_nodes_from(dict_nodes)

mod=community.modularity(partition,largest_subgraph)

plt.rcParams['figure.figsize']= [12, 8]
pos_louvain=nx.spring_layout(G_comm)
nx.draw_networkx(G_comm, pos_louvain, with_labels=True,node_size=200,font_size=11,label='Modularity =' + str(round(mod,3)) +
                    ', Communities=' + str(len(G_comm.nodes())))
plt.suptitle('Number of Communities(Louvain Algorithm)',fontsize=22,fontname='Arial')
plt.box(on=None)
plt.axis('off')
plt.legend(bbox_to_anchor=(1,0), loc='best', ncol=1)
plt.savefig('louvain1.png',dpi=400, bbox_inches='tight')

我能够得到这个,但我想看到一个图表,显示社区内部的样子。作为最大的社区,我认为社区 9 是一个理想的例子。

【问题讨论】:

    标签: matplotlib graph networkx graph-theory jsnetworkx


    【解决方案1】:

    您可以通过以下方式获取社区9中节点的subgraph

    nodes_in_community9 = [node for node,community in partition.items() if community == 9]
    S = G.subgraph(nodes_in_community9)
    

    S 将是一个 NetworkX 图,只有社区 9 中的节点和它们之间的边。不幸的是,NetworkX 可能仍然无法绘制 12,000 个节点的图表。 Gephi 等替代品可能会更好。

    【讨论】:

    • 谢谢约翰内斯。我还有一个问题,如果不是很麻烦的话。如何导出子图以便在 Gephi 上使用它?我尝试先将其转换为数据帧,但这可能有点笨拙。
    • 当然可以。您可以使用 nx.write_gexf(S,'mygraph.gexf') 或 nx.write_gml(S,'mygraph.gml') 将 NetworkX 图形写入文件扩展名 .gexf 和 .gml。在 Gephi 中,您可以通过 File/Open 打开这些文件类型中的任何一种。
    猜你喜欢
    • 2017-09-18
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 2022-11-03
    • 2015-10-05
    • 2020-01-21
    • 1970-01-01
    相关资源
    最近更新 更多