如何从 networkx 图中的边标签中删除属性?

How to remove an attribute from the edge label in a networkx graph?

如何从 networkx 图中的边标签中删除属性?

下面的例子

edgelabels = nx.get_edge_attributes(G, 'weight')

nx.draw_networkx_edges(G, pos, label_pos=0.5, alpha=0.5, edge_color='k')
nx.draw_networkx_edge_labels(G, pos, labels = edgelabels)

在每个边缘标签上打印 {'weight': n}:我想要的只是 'n'。这将使图形更加清晰。

如果要将'n'作为边缘标签,必须使用参数'edge_labels'和draw_networkx_edge_labels,而不是'labels'。

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

下面是如何为 'weight' 属性绘制数字。

import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,weight=7)
G.add_edge(2,3,weight=42)
labels = {}
for u,v,data in G.edges(data=True):
    labels[(u,v)] = data['weight']

pos = nx.spring_layout(G)
nx.draw(G,pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.show()