1

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)
FaCoffee
  • 7,609
  • 28
  • 99
  • 174
  • 1
    Keeping the same position of nodes across plots is easier if it was the same graph. It is possible to feed an initial position into the springlayout algorithm, which will result in a consistent final output. It is possible also to specify certain nodes that aren't allowed to change position if you want that as well. You can check the documentation for drawing graphs using the specific layout you are interested in. There is a very detailed answer here http://stackoverflow.com/questions/30035039/fix-position-of-subset-of-nodes-in-networkx-spring-graph – DotPi Oct 07 '16 at 14:04

2 Answers2

5

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).
Joel
  • 22,598
  • 6
  • 69
  • 93
2

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()

enter image description here

mengg
  • 310
  • 2
  • 9