0

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

根据networkx.draw 的文档, draw 函数的“pos”参数接受一个指定节点位置的字典。我看到几个例子,人们使用类似于这种模式的 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" )

谁能建议我做错了什么,或者如何生成子图的图像,其中节点与完整图的位置相同?

4

2 回答 2

3

问题不在于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" )

在此处输入图像描述 在此处输入图像描述

于 2013-10-02T02:15:04.920 回答
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" )
于 2013-10-02T18:51:01.760 回答