2017-09-04 173 views
2

我正在嘗試使用以下信息創建圖形。Python - 用節點位置繪製圖形

n = 6 #number of nodes 
    V = [] 
    V=range(n)# list of vertices 
    print("vertices",V) 
    # Create n random points 

    random.seed(1) 
    points = [] 
    pos = [] 

    pos = {i:(random.randint(0,50),random.randint(0,100)) for i in V} 
    print("pos =", pos) 

這使我的位置作爲

pos = {0: (8, 72), 1: (48, 8), 2: (16, 15), 3: (31, 97), 4: (28, 60), 5: (41, 48)} 

我想在Python使用Matplotlib來繪製與這些節點和一些邊緣(其可以在其他一些計算來獲得)的曲線圖。我已經嘗試過,如下所示。但沒有奏效。

G_1 = nx.Graph() 
    nx.set_node_attributes(G_1,'pos',pos) 
    G_1.add_nodes_from(V) # V is the set of nodes and V =range(6) 


    for (u,v) in tempedgelist: 
     G_1.add_edge(v, u, capacity=1) # tempedgelist contains my edges as a list ... ex: tempedgelist = [[0, 2], [0, 3], [1, 2], [1, 4], [5, 3]] 


    nx.draw(G_1,pos, edge_labels=True) 
    plt.show() 

可有人請幫我這...

回答

1

您只需要posnx.draw()。您可以使用add_edges_from()設置節點和邊緣。

import networkx as nx 
import random 

G_1 = nx.Graph() 
tempedgelist = [[0, 2], [0, 3], [1, 2], [1, 4], [5, 3]] 
G_1.add_edges_from(tempedgelist) 

n_nodes = 6 
pos = {i:(random.randint(0,50),random.randint(0,100)) for i in range(n_nodes)} 
nx.draw(G_1, pos, edge_labels=True) 

graph

注意:如果你需要跟蹤pointspositions分開,寫入列出了從pos

points = [] 
positions = [] 
for i in pos: 
    points.append(pos[i]) 
    positions.append(i) 
    positions.append(pos[i]) 
2

我沒有合適的IDE的權利,但一個問題我在你的代碼發現是pos應該是一本字典,看到the networkx doc here for setting node attributehere for drawing

試試這個

import networkx as nx 
import matplotlib.pyplot as plt 

g= nx.Graph() 
pos = {0:(0,0), 1:(1,2)} 
g.add_nodes_from(range(2)) 
nx.set_node_attributes(g, 'pos', pos) 
g.add_edge(0, 1) 
nx.draw(g, pos, edge_labels=True) 
plt.show() 

讓我知道,如果它的工作原理。

+0

謝謝,Nos。會嘗試它並讓你知道。 – ccc

1

你必須改變你的職位列表變爲詞典:

pos = dict(zip(pos[::2],pos[1::2])) 

順便說一下,你可以直接從邊緣列表中創建圖形(節點自動添加):

G1 = nx.Graph(tempedgelist) 
nx.set_node_attributes(G_1,'capacity',1)