问题描述
我需要绘制这些独立图形的边缘不相交的完整图形。我曾尝试在 matplotlib 中使用坐标,但没有奏效。这是代码:
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_edge("1","2")
G.add_edge("2","3")
G.add_edge("3","4")
G.add_edge("1","3")
G.add_edge("1","4")
G.add_edge("2","4")
pos = {1: (0,0),2: (1,1),3: (0,4: (1,0)}
F=nx.Graph()
F.add_edge("5","6")
F.add_edge("6","7")
F.add_edge("7","8")
F.add_edge("5","7")
F.add_edge("5","8")
F.add_edge("6","8")
pos = {5: (10,10),6: (11,11),7: (10,8: (11,10)}
E=nx.Graph()
E.add_edge("9","10")
E.add_edge("10","11")
E.add_edge("9","11")
pos = nx.random_layout(E)
Y=nx.Graph()
Y.add_node("12")
pos = nx.random_layout(Y)
nx.draw(G,with_labels = True,node_color = 'white')
nx.draw(F,node_color = 'white')
nx.draw(E,node_color = 'white')
nx.draw(Y,node_color = 'white')
plt.savefig('labels.png')
plt.show()
结果
解决方法
您创建了 pos
变量并多次覆盖它而没有在任何时候使用它。只需创建多个不重叠的绘图区域:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge("1","2")
G.add_edge("2","3")
G.add_edge("3","4")
G.add_edge("1","3")
G.add_edge("1","4")
G.add_edge("2","4")
pos_G = {"1": (0,0),"2": (1,1),"3": (0,"4": (1,0)}
F = nx.Graph()
F.add_edge("5","6")
F.add_edge("6","7")
F.add_edge("7","8")
F.add_edge("5","7")
F.add_edge("5","8")
F.add_edge("6","8")
pos_F = {"5": (10,10),"6": (11,11),"7": (10,"8": (11,10)}
E = nx.Graph()
E.add_edge("9","10")
E.add_edge("10","11")
E.add_edge("9","11")
pos_E = nx.random_layout(E)
pos_E = {node: pos + 3 for node,pos in pos_E.items()}
Y = nx.Graph()
Y.add_node("12")
pos_Y = nx.random_layout(Y)
pos_Y = {node: pos + 5 for node,pos in pos_Y.items()}
nx.draw(G,pos_G,with_labels=True,node_color='white')
nx.draw(F,pos_F,node_color='white')
nx.draw(E,pos_E,node_color='white')
nx.draw(Y,pos_Y,node_color='white')
# plt.savefig('labels.png')
plt.show()