繁体   English   中英

NetworkX:在 for 循环中绘制图形会返回错误的图形

[英]NetworkX: plotting a graph in a for loop returns the wrong graph

我正在使用我创建的常规网络(网格):

import networkx as nx
N=100
def graph_creating(N):
    G=nx.grid_2d_graph(N,N)
    pos = dict( (n, n) for n in G.nodes() ) #Dictionary of all positions
return G, pos

我有两种迭代代码的方法。 在两者中,我从网络中删除节点并尝试绘制它。 根据我是最初创建网络还是在循环内创建网络,我在绘制它时会得到不同的行为。

我的问题:我想在 stage 1stage 2之后绘制网格,以便与未更改的网格/图形进行比较。 我没有正确地做到这一点,因为:

  • 如果原始网格是在for循环之外创建的,我会正确地得到第一个图,但后来的图是空的,因为图永远不会恢复到其未更改的状态;
  • 如果原始网格是在for循环创建的,我总是最终绘制未更改的网格,就好像删除对其没有影响一样。

为了能够在第 1 阶段和第 2 阶段之后立即绘制图形,还应该将图形创建块放置在哪里?

版本 1图形是在for循环之外创建的:

G, pos = graph_creating(N)
nodelist = G.nodes()
for counter in range(5):
    G1 = nodelist[2*counter:2*counter+1]
    G.remove_nodes_from(G1)
    nx.draw_networkx(G, pos = pos)
    figurename = 'file{0}.png'.format(counter)
    plt.savefig(figurename)

    G2=nodelist[2*counter+1:2*counter+2]
    G.remove_nodes_from(G2)
    nx.draw_networkx(G,pos=pos)
    #it's not clear from your original question if you save this figure or not

结果:只有第一次迭代产生正确的图。 后面的图是空的,因为图永远不会恢复到其未更改的状态。

版本 2图形是在for循环内创建的:

for counter in range(5):
    G, pos = graph_creating(N)
    nodelist = G.nodes()
    G1 = nodelist[2*counter:2*counter+1]
    G.remove_nodes_from(G1)
    nx.draw_networkx(G, pos = pos)
    figurename = 'file{0}.png'.format(counter)
    plt.savefig(figurename)

    G2=nodelist[2*counter+1:2*counter+2]
    G.remove_nodes_from(G2)
    nx.draw_networkx(G,pos=pos)
    #it's not clear from your original question if you save this figure or not

结果:nx.draw_networkx的调用导致每次迭代都绘制未nx.draw_networkx的图形。 我想知道问题是否出在我调用该函数的方式上,因为它总是绘制没有失败节点的图形。 为什么我有这个绘图问题? .

  • 在 for 循环之外创建图形块。
  • 在 for 循环内使用tmp_G = G.copy()创建图形的副本
  • 使用draw_netwokxremove_nodes_from使用tmp_G而不是G
  • 当您想将更改后的图形与原始图形进行比较时,请使用图形G调用 draw_networkx 函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM