簡體   English   中英

向 Networkx 中的圖形節點添加(浮動)坐標 - IndexError

[英]Adding (float) coordinates to graph nodes in Networkx - IndexError

我有一個 of.txt 形式的數據集,我想將 plot 作為圖表。 這個txt提供的數據如下:

68  57
65  86
67  83
105 156

等等,所以它是一個邊緣列表。

import networkx as nx
import numpy as py
import copy
import matplotlib.pyplot as plt

network0=nx.read_edgelist(r'C:\Users\alexl\Documents\new_python\init_edgelist.txt',create_using=nx.DiGraph)

nx.draw(network0)
plt.show()

在這些之后,我可以看到一個繪制的有向圖,正如我所想的那樣,它的拓撲錯誤。 節點和邊正確連接,但沒有位置信息。 我嘗試在此 another.txt 中導入 3 列(節點 xy),例如:

2   478909.145  4204244.629

有了這個:

coordinates=py.loadtxt(r'C:\Users\alexl\Documents\new_python\nodes_coordinates.txt')
pos=coordinates
nx.draw(network0,pos=pos,with_labels=True)
plt.show()

但似乎沒有工作。 IndexError: only integers, slices ( : ), ellipsis ( ... ), numpy.newaxis ( None ) and integer or boolean arrays are valid indices. <<< 這就是我嘗試運行它時在控制台中顯示的內容。 我想這與坐標是浮動的事實有關? 或者由 txt 他們組成一個列表,我們想要一本字典? 之后我想向邊緣添加權重(0,1,2),但首先我想看到我的數據在拓撲方面“正確”繪制。

當鍵是節點而值是位置時, nx.draw期望pos是一個字典。

假設您想將輸入讀取為 numpy 數組,您可以做的是

pos = dict(zip(coordinates[:,0].astype(int), coordinates[:,1:]))
nx.draw(network0, pos=pos, with_labels=True)

否則,您可以只遍歷文件的行並直接構建字典。

pos = {}
with open('coords.txt') as f:
    for line in f:
        node, x, y = line.split()
        pos[node] = float(x), float(y)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM