Python - 绘制带有节点位置的图形

Python - draw a graph with node positions

我正在尝试使用以下信息创建图表。

    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()

有人可以帮我解决这个问题吗...

我现在没有合适的 IDE,但我在您的代码中发现的一个问题是 pos 应该是一本字典,请参阅 the networkx doc here for setting node attribute and 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()

如果有效请告诉我。

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)

注意:如果您需要分别跟踪 pointspositions,请从 pos:

写入列表
points = []
positions = []
for i in pos:
    points.append(pos[i])
    positions.append(i)
    positions.append(pos[i])

您必须将职位列表转换成字典:

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

顺便说一句,您可以直接从边列表构建图(节点是自动添加的):

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