从文件中读取标签的Python 3有向图

2 投票
1 回答
2811 浏览
提问于 2025-04-18 14:02

我有一个文件,里面的行像这样(node1; node2; label-weight)

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

每行的前两个部分是一个网络图中的节点。第三部分是边的标签(或者说是权重或长度)。我现在用的是Python 3.4和networkx 1.9,我想在边的旁边或者里面显示标签(如果权重、标签和边的粗细都能一样就更好了)。

但是用我现在的代码,画出的边上没有标签。

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

我看到可以用字典来添加带标签的边。我正在研究这个,但目前这个方法对我来说还是太复杂了。

谢谢。

1 个回答

3

你确实走在正确的道路上,但你的代码有几个问题。

  1. 你的示例文件在分号后面有空格,所以你也需要在这些空格上进行分割。

    node1, node2, weight1 = line.strip().split("; ")
    
  2. 你的权重看起来是浮点数,而不是整数(就像你示例中那样),所以你需要把权重中的 "," 替换成 "."。(另外一个选择是查看一下 locale模块。)

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

这是你的输出图:

带权重边标签的输出图

撰写回答