首页 > 解决方案 > 在 Networkx 中组合图:将图添加为子节点

问题描述

我有两个图表。

Graph_1 是一个有向无环图 (DAG),它在 df_1 中具有以下边列表:

node_1  node_2
John    Charity
John    Constantine
Gordon  John
Gordon  Nick

Graph_1 = nx.from_pandas_edgelist(df_1, source="node_1", 
                                       target="node_2", create_using=nx.DiGraph())

Graph_2 是一个随机随机图,生成如下:

Graph_2 = nx.erdos_renyi_graph(1000, 0.1)

我想通过使 Graph_2 中具有最高中介中心性的节点成为 Graph_1 中“尼克”节点的子节点,将 Graph_2 加入到 Graph_1。

有人对我如何做到这一点有任何想法吗?

标签: networkxdirected-acyclic-graphs

解决方案


以下应该工作

import networkx as nx
import matplotlib.pylab as pl

edge_list = [
    ["John", "Charity"],
    ["John", "Constantine"],
    ["Gordon", "John"],
    ["Gordon", "Nick"], ]

Graph_1 = nx.from_edgelist(edge_list, create_using=nx.DiGraph())

# reduced the number for visualization
Graph_2 = nx.erdos_renyi_graph(10, 0.1)

node_with_highest_betweenness_centrality = max(nx.betweenness_centrality(Graph_2).items(), key=lambda x: x[1])[0]

joined_graph = nx.DiGraph(Graph_1)

joined_graph.add_edges_from(Graph_2.edges())
# not sure which direction you want
joined_graph.add_edge(node_with_highest_betweenness_centrality, "Nick")

nx.draw(joined_graph, with_labels=True)
pl.show()

在此处输入图像描述


推荐阅读