如何绘制具有多个边属性的 networkx 图?

How to plot networkx graph with several edge attributes?

我有一个图表,其中每条边都有两个属性 'mark' 和 'cable_name'。我的目标是通过同时显示两个属性来绘制它,一个在另一个之上:

import networkx as nx
import matplotlib.pyplot as plt    

G = nx.Graph()
G.add_edge(1, 2,  mark='200', cable_name='К300')

pos = nx.spring_layout(G, scale=2)    
edge_labels = nx.get_edge_attributes(G, 'mark')
nx.draw_networkx_edge_labels(G, pos, edge_labels)
nx.draw(G, with_labels = True, nodecolor='r', edge_color='b')
plt.show()

它只显示一个属性 'mark',正如我从 documentation 获得的 get_edge_attributes 函数其属性 'name' 在只能是字符串,不能是字符串列表。

有没有可能像这样同时显示两个属性?

您可以通过将要显示在绘图上的标签关联到键(即边缘)来自定义边缘标签。

示例:

  1. 格式化标签

    edge_labels = {}
    # this assumes all the edges have the same labels 'marks' and 'cable_name' 
    for u, v, data in G.edges(data=True):
        edge_labels[u, v] = f"{data['mark']}\n{data['cable_name']}"
    
  2. 将带有属性的整个字典添加为边标签

    edge_labels = {}
    for u, v, data in G.edges(data=True):
        edge_labels[u, v] = data