我需要一个包含 N 个簇的图,它在某种程度上代表了社交网络的结构。我计划通过使用 barabasi albert 结构创建 N 个图,然后通过单个节点连接它们来解决这个问题。
import networkx as nx
a = nx.barabasi_albert_graph(10,2)
b = nx.barabasi_albert_graph(10,2)
nx.draw(a)
nx.draw(b)
我想要的是它们像这样连接: 但是我看不到或找不到任何简单的方法来做到这一点,是否有任何 networkX 功能可以做到这一点?
请您参考如下方法:
通过边连接两个图非常简单:
import matplotlib.pyplot as plt
import networkx as nx
a = nx.barabasi_albert_graph(10,2)
b = nx.barabasi_albert_graph(10,2)
c = nx.union(a,b, rename=('a-', 'b-'))
c.add_edge('a-0', 'b-0')
nx.draw_networkx(c,with_labels=True,node_size=500)
plt.show()
如果你想在一个公共(public)节点上合并图(这在你的问题中与标题相反),你可以这样做:
import matplotlib.pyplot as plt
import networkx as nx
a = nx.barabasi_albert_graph(10,2)
b = nx.barabasi_albert_graph(10,2)
a= nx.relabel_nodes(a, { n: str(n) if n==0 else 'a-'+str(n) for n in a.nodes })
b= nx.relabel_nodes(b, { n: str(n) if n==0 else 'b-'+str(n) for n in b.nodes })
c = nx.compose(a,b)
nx.draw_networkx(c,with_labels=True,node_size=500)
plt.show()
