Skip to main content
 首页 » 编程设计

python之使用 Python 中的 networkX 包绘制图形分区

2025年05月04日8zhujiabin

我有一个图对象 G,节点从 0 到 n-1 和两个列表 L1 L2是G节点的划分。我想以这样一种方式绘制 G,即节点结果分为两个 block :一个相对于 L1,另一个相对于 L2。图片的目的应该是证明 L1 和 L2 之间的联系。你能帮我完成这个任务吗?

非常感谢。

请您参考如下方法:

分别绘制每个图并使用不相交的乘积生成显示边的新图:

import networkx as nx 
 
n1, n2 = 10, 10 
 
# Define two random graphs 
g1 = nx.gnm_random_graph(n1,20) 
g2 = nx.gnm_random_graph(n2,20) 
pos1 = nx.graphviz_layout(g1,prog='dot') 
pos2 = nx.graphviz_layout(g2,prog='dot') 
 
# Shift graph2 
shift = 400 
for key in pos2: 
    pos2[key] = (pos2[key][0]+shift, pos2[key][1]) 
 
# Combine the graphs and remove all edges 
g12 = nx.disjoint_union(g1,g2) 
for i,j in g12.edges(): 
    g12.remove_edge(i,j) 
 
# Add the conjoined edges 
g12.add_edge(5, 7+n1) 
g12.add_edge(2, 3+n1) 
g12.add_edge(8, 7+n1) 
 
# Set the new pos for g12 
pos12 = pos1.copy() 
for node in pos2: 
    pos12[node+n2] = pos2[node] 
 
# Show the results, make the conjoined edges darker 
 
import pylab as plt 
nx.draw_networkx(g1,pos=pos1,alpha=0.5) 
nx.draw_networkx(g2,pos=pos2,alpha=0.5) 
nx.draw_networkx_edges(g12,pos=pos12,width=5) 
plt.axis('off') 
plt.show()