networkx:从两个图形连接相同的节点 [英] networkx: connect the same nodes from two graphs

查看:483
本文介绍了networkx:从两个图形连接相同的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python,NetworkX和Matplotlib,我想从两个图形连接同一节点 例如 两个图:G1和G2

I am using python, NetworkX and Matplotlib, I want to connect same node from two graphs For example two graphs:G1 and G2

G1=nx.Graph()
G2=nx.Graph()
G1.add_nodes_from([0,1,2,3,9,8,10,11,12,13,14])
G2.add_nodes_from([4,5,6,7,8])
G1.add_edges_from([(0,1),(2,3),(2,9),(2,12),(1,9),(10,8),(8,11),(8,13),(8,14)])
G2.add_edges_from([(4,5),(6,7),(4,8)])
pos1=nx.spring_layout(G1,k=0.2,iterations=30)
pos2=nx.spring_layout(G2)
for k,v in pos2.items():
    v[0] = v[0] +3
nx.draw(G1,pos1,with_labels=True,node_color='b')
nx.draw(G2,pos2,with_labels=True)

图片是这样的:

我的问题是如何从两个图形连接相同的节点? (两个节点均为"8")

My question is how can I connect the same nodes from two graphs? (node "8" is in both of them)

我想要 节点"8"(蓝色)与节点"8"(红色)链接.

I want node"8"(blue) link with node"8"(red).      

我还使用了G3 = nx.compos(G1,G2), 但我不知道如何在右侧绘制节点(color = blue,来自G1),在左侧绘制其他节点(color = red,来自G2). 所以我放弃了这种方法.

I also used G3= nx.compos(G1,G2), but I don't know how to draw the nodes(color =blue,from G1) at the right side and the other nodes at the left side(color =red, from G2). So I gave up this method.

推荐答案

好,最后我决定使用nx.compose的方法,它已经成功了 在命令中的pos2行之后,添加以下内容:

OK, finally I decided use the method of nx.compose and It' worked After the line pos2 in the command, add those:

D_1=G2.nodes()
G3=nx.compose(G1,G2)
pos3= nx.spring_layout(G3)
for k, v in pos3.items():
    if k in D_1:
        v[0] = v[0] +10 
nx.draw_networkx_nodes(G3,pos3,nodelist=G1.nodes(),node_color='b')
nx.draw_networkx_nodes(G3,pos3,nodelist=G2.nodes())
nx.draw_networkx_edges(G3,pos3,edgelist=G1.edges())
nx.draw_networkx_edges(G3,pos3,edgelist=G2.edges())
nx.draw_networkx_labels(G3,pos3)

图片将变为此

这篇关于networkx:从两个图形连接相同的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆