python 3有向图,带有文件中的标签

标签 python networkx label

我有一个文件,其中包含这样的行(node1; node2; label-weight)

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

该行中的第一个和第二个元素是 networkx 图的节点。第三个是边缘的标签(或重量或长度)。 我正在使用 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. 您的示例文件在分号后面有空格,因此您也应该在这些空格上进行拆分。

    node1, node2, weight1 = line.strip().split("; ")
    
  2. 您的权重似乎是 float 而不是整数(如您的示例中所示),因此您需要 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

关于python 3有向图,带有文件中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24852297/

相关文章:

python - Pandas: AttributeError: 'Series' 对象没有属性 'style'

python - 从 grid_2d_graph 中一致删除节点

c# - 如何在 C# 中更改 MS 图表标签字体大小?

html - ipad 上带有 div 的复选框标签不可点击

python - 有没有办法阻止 django View 同时处理多个请求?

python - 逐步将新数据附加并绘制到 matplotlib 行

python - 为什么我的代码无法绘制有向图的箭头?

python - 根据 networkx 中的边权重排序的相邻边(Python)

ios - 链接的 TTTAttributedLabel 和弹出窗口

python - shebang env首选python版本