简体   繁体   中英

NetworkX: plotting the same graph first intact and then with a few nodes removed

Say I have a graph with 10 nodes, and I want to plot it when:

  1. It is intact
  2. It has had a couple of nodes removed

How can I make sure that the second plot has exactly the same positions as the first one?

My attempt generates two graphs that are drawn with a different layout:

import networkx as nx
import matplotlib.pyplot as plt
%pylab inline

#Intact
G=nx.barabasi_albert_graph(10,3)
fig1=nx.draw_networkx(G)

#Two nodes are removed
e=[4,6]
G.remove_nodes_from(e)
plt.figure()
fig2=nx.draw_networkx(G)

The drawing commands for networkx accept an argument pos .

So before creating fig1 , define pos The two lines should be

pos = nx.spring_layout(G) #other layout commands are available.
fig1 = nx.draw_networkx(G, pos = pos)

later you will do

fig2 = nx.draw_networkx(G, pos=pos).

The following works for me:

import networkx as nx
import matplotlib.pyplot as plt
from random import random


figure = plt.figure()
#Intact
G=nx.barabasi_albert_graph(10,3)

node_pose = {}
for i in G.nodes_iter():
    node_pose[i] = (random(),random())

plt.subplot(121)
fig1 = nx.draw_networkx(G,pos=node_pose, fixed=node_pose.keys())

#Two nodes are removed
e=[4,6]
G.remove_nodes_from(e)
plt.subplot(122)
fig2 = nx.draw_networkx(G,pos=node_pose, fixed=node_pose.keys())


plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM