networkx - 在 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。
有人对我如何做到这一点有任何想法吗?
解决方案
以下应该工作
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()
推荐阅读
- r - 如何在 R 中另一个数据集的列中选择一个数据集中的某些行?
- python - 如何使用双 for 循环将元素名称添加到结果中?
- python - 即使是使用多处理池的简单教程代码也永远不会启动
- .net - 在文本文件中使用逗号分隔值打印输出
- html - 为什么锚元素的 `color:initial` 将其颜色设置为黑色而不是蓝色?
- java - Spring postConstruct不会加载messageSource中的所有消息
- php - 为空时更新值
- git - 创建一个适合功能更改的新分支是否仅限于 git 中的单个脚本文件?
- google-apps-script - 谷歌脚本如何比较两列中的单元格并将值设置为另一个单元格
- excel - 当工作簿受 vba 保护时,如何修复禁用的 excel 宏文件?