如何在使用NetworkX可视化图时固定节点位置。

huangapple go评论69阅读模式
英文:

how to fix the location of nodes while visualizing graph in networkx

问题

我正在可视化生成的随机图表。我将按照某些规则更改每个节点的颜色,并希望追踪图表节点颜色的变化。(也许我可以使用图表的图像制作gif)

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
n = 50
p = 0.12

np.random.seed(42)

G = nx.gnp_random_graph(n, p)
color_map = np.random.choice(['blue', 'red'], size=50)
nx.draw(G, node_color=color_map, with_labels=True)
plt.savefig('2.png')
nx.draw(G, node_color=color_map, with_labels=True)
plt.savefig('3.png')

2.png
3.png

但我发现每次绘制时节点的位置都会改变。我期望这两幅图重叠完美,看起来像一张图。但如你所见,在第二张图中,每个节点的位置都改变了。我该如何固定节点的位置?

另一种生成随机图的方法

英文:

I'm visualizing graph , which generated ramdomly. I will change color of each node in some rules and wanna track change of graph nodes' color. (Maybe I can make gif with the images of graph)

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
n = 50
p = 0.12

np.random.seed(42)

G = nx.gnp_random_graph(n, p)
color_map = np.random.choice(['blue', 'red'], size=50)
nx.draw(G, node_color=color_map, with_labels=True)
plt.savefig('2.png')
nx.draw(G, node_color=color_map, with_labels=True)
plt.savefig('3.png')

2.png
3.png

but I found put that the nodes' location change every time I plot. I expected that the two drawings would overlap perfectly and look like one. but as you can see in the second plot, every node's location changed. How can I fix nodes' location?

another way to make random graph

答案1

得分: 1

The nx.draw functions have a parameter pos that lets you supply a pre-calculated dictionary of positions keyed by node.

因此,您可以在第一个 nx.draw 之前使用 pos = nx.spring_layout(G),然后将 pos = pos 添加到每个后续 nx.draw 的参数中。

英文:

The nx.draw functions have a parameter pos that lets you supply a pre-calculated dictionary of positions keyed by node.

Therefore, you can use pos = nx.spring_layout(G) before the first nx.draw, then add pos = pos into the parameters of each subsequent nx.draw

huangapple
  • 本文由 发表于 2023年5月10日 21:17:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定