networkx.draw()的pos参数无法正常工作

2024-10-01 13:36:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

基于documentation for networkx.draw the "pos" argumentto,draw函数接受指定节点位置的字典。我看到了几个例子,人们使用与此模式类似的pos参数:

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

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

这是一个简单的复制机,演示了这个问题。我认为这段代码应该创建两个.png文件,包含两个图形“g”和“h”。节点“c”和“d”在“h”的绘图中应该与它们在“g”中的位置相同-但是它们不是。在

^{pr2}$

有谁能建议我做错了什么,或者如何生成子图的图像,这些子图的节点与整个图的节点位于同一位置?在


Tags: the函数pos图像networkxfor参数字典
2条回答

以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" )

问题不在于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 hereenter image description here

相关问题 更多 >