如何使用类似 nxpd 的输出来表示具有边权重的 networkx 图

How to represent networkx graphs with edge weight using nxpd like outptut

最近我问了这个问题。答案正是我要找的,但今天我正在寻找一种在最终图片上显示边缘估值的方法。

边缘估值是这样添加的:

import networkx as nx
from nxpd import draw # If another library do the same or nearly the same
                      # output of nxpd and answer to the question, that's
                      # not an issue
import random

G = nx.Graph()
G.add_nodes_from([1,2])
G.add_edge(1, 2, weight=random.randint(1, 10))

draw(G, show='ipynb')

结果就在这里。

我阅读了 nxpd.drawhelp(没有看到任何网络文档),但我没有找到任何东西。 有没有办法打印边缘值?

EDIT :此外,如果有一种方法可以提供格式化功能,这可能会很好。例如:

def edge_formater(graph, edge):
    return "My edge %s" % graph.get_edge_value(edge[0], edge[1], "weight")

EDIT2 :如果除了 nxpd 之外还有另一个库做几乎相同的输出,那不是问题

EDIT3 :必须使用 nx.{Graph|DiGraph|MultiGraph|MultiDiGraph}

如果您查看 source nxpd.draw(函数 draw_pydot)调用 to_pydot,它过滤图形属性,例如:

if attr_type == 'edge':
    accepted = pydot.EDGE_ATTRIBUTES
elif attr_type == 'graph':
    accepted = pydot.GRAPH_ATTRIBUTES
elif attr_type == 'node':
    accepted = pydot.NODE_ATTRIBUTES
else:
    raise Exception("Invalid attr_type.")

d = dict( [(k,v) for (k,v) in attrs.items() if k in accepted] )

如果您查找 pydot,您会找到包含有效 Graphviz 属性的 pydot.EDGE_ATTRIBUTES。如果我记得的话,weight 严格指的是 Graphviz 的边权重,而 label 可能是您需要的属性。尝试:

G = nx.Graph()
G.add_nodes_from([1,2])
weight=random.randint(1, 10)
G.add_edge(1, 2, weight=weight, label=str(weight))

请注意,我无法测试这是否有效,如果无效,请投反对票。