在 Networkx 中组合图:将图添加为子节点
Combine Graphs in Networkx: Adding Graphs as Daughter Nodes
我有两个图表。
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 中“Nick”节点的子节点].
有人知道我该怎么做吗?
以下应该有效
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()
我有两个图表。
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 中“Nick”节点的子节点].
有人知道我该怎么做吗?
以下应该有效
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()