netx.draw()的pos参数不起作用

时间:2013-10-02 02:03:52

标签: python matplotlib networkx

我正在尝试生成图表子图的图像,其中节点应出现在两个图的相同位置。

基于绘制函数的documentation for networkx.draw the "pos" argument接受一个指定节点位置的字典。我看到几个人们使用类似于这种模式的pos参数的例子:

positions = networkx.spring_layout( GraphObject )
networkx.draw( GraphObject, positions )

然而,当我尝试这个时,我发现位置显然被忽略了 - 或者至少当我绘制图形并记录其节点的位置时,然后使用该字典作为pos参数来绘制子图的相应节点不会在相同的位置绘制。

这是一个简单的重现器,可以演示这个问题。我认为这段代码应该做的是创建两个图形“g”和“h”的两个.png文件。节点“c”和“d”应该在“h”的图形中与“g”中的位置相同 - 但它们不是。

#!/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" )

任何人都可以建议我做错了什么,或者如何生成子图的图像,其中节点与完整图的位置在同一位置?

2 个答案:

答案 0 :(得分:2)

问题不在于networkx是错误的行为,而是两个数字中的x和y限制是不同的

# Define the positions of a, b, c, d
positions = nx.spring_layout( g )
plt.figure()
# Produce image of graph g with a, b, c, d and some edges.
nx.draw( g, positions )
#plt.savefig( "g.png" )
_xlim = plt.gca().get_xlim() # grab the xlims
_ylim = plt.gca().get_ylim() # grab the ylims
# Clear the figure.
# plt.clf()
plt.figure()
# 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.gca().set_xlim(_xlim) # set the xlims
plt.gca().set_ylim(_ylim) # set the ylims
# plt.savefig( "h.png" )

enter image description here enter image description here

答案 1 :(得分:1)

以tcaswell的提示为出发点,我发现这对我有用:

#!/usr/bin/python

import matplotlib.pyplot as plt
import networkx as nx

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 )

nx.draw( g, positions )

# Save the computed x and y dimensions for the entire drawing region of graph g
xlim = plt.gca().get_xlim()
ylim = plt.gca().get_ylim()

# Produce image of graph g with a, b, c, d and some edges.
plt.savefig( "g.png" )
#plt.show()

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

# Ensure the drawing area and proportions are the same as for graph g.
plt.axis( [ xlim[0], xlim[1], ylim[0], ylim[1] ] )

#plt.show()
plt.savefig( "h.png" )