【问题标题】:Draw nodes in fixed position with coordinates in Networks python [closed]在网络python中使用坐标在固定位置绘制节点[关闭]
【发布时间】:2018-05-10 10:08:56
【问题描述】:

我正在尝试使用属性“名称”、“纬度”和“经度”来绘制节点。我试图用下面的代码来绘制它,但它每次都返回不同的图形。如何固定节点的位置?

G = nx.Graph()

G.add_nodes_from(pos.keys())
for n, p in pos.items():
   G.node[n]['pos'] = p

pos=nx.spring_layout(G)
pos=nx.get_node_attributes(G,'pos')
pos=nx.spring_layout(G)

nx.draw(G, pos, with_labels=True, font_size=8, node_size=5)
plt.show()

下面是第 3 行 pos 的例子。

{'Baker Street': [51.522236, -0.15708], 'Bermondsey': [51.498129999999996, -0.0635], 'Blackhorse Road': [51.58698, -0.04104]}

【问题讨论】:

  • Spring 布局将节点置于随机位置。所以每次调用 spring layout 都会产生不同的东西。把你用pos=nx.spring_layout(G)的两次去掉,直接用pos=nx.get_node_attributes(G, 'pos')就行了。

标签: python coordinates networkx


【解决方案1】:

首先将所有节点添加到 G,然后使用 G.nodes() 作为键创建一个字典。

self.pos = dict(zip(self.graph.nodes(), pos_list))

其中 pos_list 是包含坐标的元组列表。

【讨论】:

  • 感谢您的评论。它返回相同的随机图。
【解决方案2】:

您正在使用spring 布局,这与您的目标位置不同。这就是为什么你得到不同的布局。为了将节点的位置固定到属性position,只需这样做:

import networkx as nx

G = nx.Graph()

G.add_nodes_from(pos.keys())
for n, p in pos.items():
   G.nodes[n]['pos'] = p


nx.draw(G, pos=pos, with_labels=True, font_size=8, node_size=5)
plt.show()

【讨论】:

  • 感谢您的评论!是的,我没有足够的关于弹簧布局的信息。
猜你喜欢
  • 2023-02-07
  • 1970-01-01
  • 2018-08-25
  • 2016-05-07
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
相关资源
最近更新 更多