在两个节点集之间以不同方式绘制边

Draw edges differentially between two node sets

目标是在 G1 和 G2 之间绘制虚线连接的双射图。

我有两个节点集 g1 和 g2。

g1.nodes = NodeView((0, 1, 2))
g2.nodes = NodeView(('a', 'b', 'c', 'd', 'e'))

它们由边连接:

g1.edges = EdgeView([(0, 1), (0, 2), (1, 2)])
g2.edges = EdgeView([('a', 'b'), ('a', 'c'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')])

这是执行上述步骤的代码:

import string
import networkx as nx
import numpy as np

g1, g2 = nx.Graph(), nx.Graph()

g1.add_nodes_from([0, 1, 2])

tmp = [i for i in range(0, 5)]
tmp = np.array(list(string.ascii_lowercase))[tmp]

g2.add_nodes_from(tmp)

g1.add_edges_from([(0, 1), (0, 2), (1, 2)])

g2.add_edges_from([('a', 'b'), ('a', 'c'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')])

我们可以想象:

figure(figsize = (10, 10))
G = nx.grid_2d_graph(4, 4)
pos = nx.spring_layout(G, iterations=100, seed=39775)


plt.subplot(221)
draw(g1, with_labels = True)

plt.subplot(222)
draw(g2, with_labels = True

我想在 G1 中选定的 u 到 G2 中选定的 v 之间绘制虚线边,同时保持各自 G1 和 G2 的二分布局和连接。

这是我目前的尝试:

# create new graph H
H = nx.Graph()
# add existing nodes and edges
H.add_nodes_from(g1.nodes, bipartite = 0)
H.add_nodes_from(g2.nodes, bipartite = 1)

new = [(0, 'd'), (1, 'c'), (2, 'b')]
H.add_edges_from(new, style = 'dashed')
draw_networkx(H, pos = nx.drawing.layout.bipartite_layout(H, g1.nodes), width = 2, style = 'dashed')

保持 G1 和 G2 结构,类似于上面的第一组图,是问题所在。添加预先存在的边会产生以下意外输出。

H.add_edges_from(g1.edges)
H.add_edges_from(g2.edges)
draw_networkx(H, pos = nx.drawing.layout.bipartite_layout(H, g1.nodes), width = 2, style = 'dashed')

我想要的是 [(0, 'd'), (1, 'c'), (2, 'b')] 之间的虚线,同时保持 G1 和来自第一张图片的 G2 二分布局和各自的边缘结构。

您需要检索每个图形的 pos 字典,然后可以自由移动它(移动坐标)。然后你可以轻松添加虚线边缘:

import string
import networkx as nx
import numpy as np
import matplotlib.pylab as plt

g1, g2 = nx.Graph(), nx.Graph()

g1.add_nodes_from([0, 1, 2])

tmp = [i for i in range(0, 5)]
tmp = np.array(list(string.ascii_lowercase))[tmp]

g2.add_nodes_from(tmp)

g1.add_edges_from([(0, 1), (0, 2), (1, 2)])

g2.add_edges_from([('a', 'b'), ('a', 'c'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')])

pos_1 = nx.spring_layout(g1)
pos_2 = nx.spring_layout(g2)

# shift pos_2
print(pos_2)
for node in g2:
    pos_2[node][0] += 3

# draw original graphs
nx.draw(g1, pos_1, with_labels=True)
nx.draw(g2, pos_2, with_labels=True)

# add dashed lines
H = nx.Graph()
new = [(0, 'd'), (1, 'c'), (2, 'b')]
H.add_edges_from(new, style='dashed')
nx.draw_networkx(H, pos=dict(pos_1, **pos_2), width=2, style='dashed')

plt.show()

结果: