在 networkx 中标记边

新手上路,请多包涵

我正在编写一个基本的神经网络,并想将其绘制成图片。为此,我创建了我需要的所有节点和边。

     for l, j in zip(self.layers, range(len(self.layers))):
        for n, i in zip(l.neurons, range(len(l.neurons))):
            fixed_positions[n.identifier] = (j, i)
    for l in self.layers:
        for n in l.neurons:
            for c, w in zip(n.inconnections, n.inconnectionweights):
               g.add_edge(n.identifier, c.identifier)
    fixed_nodes = fixed_positions.keys()
    pos = nx.spring_layout(g, pos=fixed_positions, fixed=fixed_nodes)

在此处输入图像描述

蓝点(想象它们在所有边缘上)是我想在边缘上添加标签的地方,但我不知道该怎么做。它应该适用于任何合理的网络大小,即它也适用于相应层中的 4、3 和 2 个神经元。

原文由 Eumel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

这是一个在networkx中绘制边标签的例子,希望对你有帮助。

 import matplotlib.pyplot as plt
import networkx as nx

edges = [['A', 'B'], ['B', 'C'], ['B', 'D']]
G = nx.Graph()
G.add_edges_from(edges)
pos = nx.spring_layout(G)
plt.figure()
nx.draw(
    G, pos, edge_color='black', width=1, linewidths=1,
    node_size=500, node_color='pink', alpha=0.9,
    labels={node: node for node in G.nodes()}
)
nx.draw_networkx_edge_labels(
    G, pos,
    edge_labels={('A', 'B'): 'AB',
                 ('B', 'C'): 'BC',
                 ('B', 'D'): 'BD'},
    font_color='red'
)
plt.axis('off')
plt.show()

边缘标签

原文由 Wubin Ding 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 draw_networkx_edge_labels(edge_labels) 在边缘之间绘制标签。

  • 如果未给出 edge_labels ,则使用边的属性。
  • edge_labels 应该是由边二元组文本标签键入的字典。仅绘制字典中键的标签。

要遍历图形的边缘,您可以使用 G.edges

  • G.edges returns a list of (node1, node2) , where node1 and node2 are two nodes of the edge.
  • G.edges(data=True) 返回 (node1, node2, ddict) 的列表,其中 ddict 是边属性字典。
  • G.edges(data=attr) 返回列表 (node1, node2, ddict[attr])
 import matplotlib.pyplot as plt
import networkx as nx

G = nx.DiGraph()

G.add_edges_from([(1, 2), (1, 3), (2, 3)])

pos = nx.spring_layout(G)

nx.draw_networkx(G, pos)

edge_labels = dict([((n1, n2), f'{n1}->{n2}')
                    for n1, n2 in G.edges])

nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

plt.show()

在此处输入图像描述

随着 G.edges(data=True)

 import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_edge(1, 2, weight=3)
G.add_edge(2, 3, weight=5)

pos = nx.spring_layout(G)

nx.draw(G, pos, with_labels=True)

edge_labels = dict([((n1, n2), d['weight'])
                    for n1, n2, d in G.edges(data=True)])

nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, label_pos=0.9,
                             font_color='red', font_size=16, font_weight='bold')

plt.show()

在此处输入图像描述

原文由 Ynjxsjmh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题