2014-07-20 15 views
0

涉及帶有標籤圖形我有這樣的行的文件(節點1;節點2;標籤重量)蟒3從文件

497014; 5674; 200 
5674; 5831; 400 
410912; 5674; 68,5 
7481; 5674; 150 
5831; 5674; 200 

第一和行中的第二元件是一個networkx圖的節點。第三個是邊緣的標籤(或重量或長度)。 我正在使用python 3.4和networkx 1.9,我想繪製邊緣附近或內部的標籤(如果weight = label =邊緣的厚度會很好)

使用此代碼繪製邊緣don'沒有標籤。

import networkx as nx 
import matplotlib.pyplot as plt 
data= open("C:\\Users\\User\\Desktop\\test.csv", "r") 
G = nx.DiGraph() 

for line in data: 
    (node1, node2, weight1) = (line.strip()).split(";") 
    G.add_edge(node1, node2, label=str(weight1),length=int(weight1)) 

nx.draw_networkx(G) 
plt.show() 

我已經看到可以使用字典添加帶有標籤的邊緣。我正在處理這個問題,但目前這個解決方案離我太遠了。

謝謝。

回答

2

你絕對是在正確的軌道上,但是你的代碼有幾個問題。

  1. 你的示例文件在分號後有空格,所以你也應該在這些空格上分開。

    node1, node2, weight1 = line.strip().split("; ") 
    
  2. 你的權重似乎是花車,而不是整數(如你的例子),所以你需要replace在你的權重",""."。 (另一種方法是檢查出locale module

    weight1 = weight1.replace(",", ".") 
    
  3. 要創建字典邊緣的標籤,所有你需要做的是每個邊(對節點)在其標籤,就像這樣:

    edge_labels[(node1, node2)] = float(weight1) 
    

    然後就可以調用draw_networkx_edge_labels與圖形的其餘部分繪製邊緣標籤:

    pos = nx.spring_layout(G) 
    nx.draw_networkx(G, pos=pos) 
    nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) 
    

全部放在一起,這裏的所有代碼,你需要

import networkx as nx 
import matplotlib.pyplot as plt 

data= open("test.txt", "r") # replace with the path to your edge file 
G = nx.DiGraph() 
edge_labels = dict() 
for line in data: 
    node1, node2, weight1 = line.strip().split("; ") 
    length = float(weight1.replace(",", ".")) # the length should be a float 
    G.add_edge(node1, node2, label=str(weight1), length=length) 
    edge_labels[(node1, node2)] = weight1 # store the string version as a label 

# Draw the graph 
pos = nx.spring_layout(G) # set the positions of the nodes/edges/labels 
nx.draw_networkx(G, pos=pos) # draw everything but the edge labels 
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) 
plt.show() 

而且這裏是你的輸出圖:

output graph with weighted edge labels

+0

偉大的工作,MDML,它的工作。現在我有字典的問題。事實上,如果您繪製不同時間的相同圖形,則在相同節點之間的邊緣將具有不同的值作爲標籤 – Dan