微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何绘制具有几个边缘属性的networkx图?

我有一个图,其中每个边都有两个属性标记”和“电缆名称”。我的目标是通过一次显示两个属性来绘制它,一个显示在另一个之上:

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()

enter image description here

它仅显示一个属性标记”,正如我从documentation中获得的 get_edge_attributes 函数一样,其属性名称”只能是一个字符串,而不是字符串列表。 / p>

是否有可能以这种方式显示两个属性

enter image description here

解决方法

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

示例:

  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
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。