2017-09-04 1 views
2

다음 정보로 그래프를 만들려고합니다. 내가 파이썬하기 matplotlib를 사용하여 이러한 노드 (다른 계산을 얻을 수있다) 일부 가장자리와 그래프를 그리려는 Python - 노드 위치가있는 그래프 그리기

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

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) 

이 내 위치를 제공합니다. 나는 다음과 같이 그것을 시도했다. 그러나 일하지 않았다.

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

nx.draw()에 대해서만 pos이 필요합니다. 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 attribute을 볼 것을 내가 코드에서 발견 한 문제는 및 here 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

감사합니다. – ccc

1

당신은 사전에 위치 목록을 변환해야합니다

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

덧붙여, 가장자리 목록에서 직접 그래프를 만들 수 있습니다 (노드가 자동으로 추가됨).

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