Tuesday, 1 October 2013

pos argument to networkx.draw() not working

pos argument to networkx.draw() not working

I'm trying to generate images of subgraphs of a graph where nodes should
appear in the same locations for both graphs.
Based on the documentation for networkx.draw the "pos" argument to the
draw function accepts a dictionary which specifies the positions of the
nodes. I see several examples where people use the pos argument similar to
this pattern:
positions = networkx.spring_layout( GraphObject )
networkx.draw( GraphObject, positions )
However, when I try this I find that the positions is apparently ignored -
or at least when I draw a graph and record the position of its nodes, and
then use that dictionary as the pos argument for drawing a subgraph the
corresponding nodes are not plotted in the same locations.
Here is a simple reproducer that demonstrates the problem. I think what
this code should do is create two .png files of two graphs "g" and "h."
The nodes "c" and "d" should be in the same position in the drawing of "h"
as they are in "g" - however they are not.
#!/usr/bin/python
import matplotlib.pyplot as plt
import networkx as nx
import pylab
g = nx.Graph()
g.add_node( 'a' )
g.add_node( 'b' )
g.add_node( 'c' )
g.add_node( 'd' )
g.add_edge( 'a', 'b' )
g.add_edge( 'c', 'd' )
h = nx.Graph()
h.add_node( 'c' )
h.add_node( 'd' )
# Define the positions of a, b, c, d
positions = nx.spring_layout( g )
# Produce image of graph g with a, b, c, d and some edges.
nx.draw( g, positions )
plt.savefig( "g.png" )
# Clear the figure.
plt.clf()
# Produce image of graph h with two nodes c and d which should be in
# the same positions of those of graph g's nodes c and d.
nx.draw( h, positions )
plt.savefig( "h.png" )
Can anyone please suggest what I'm doing wrong, or how to generate images
of subgraphs where the nodes are in the same location as that of the full
graph?

No comments:

Post a Comment