为了账号安全,请及时绑定邮箱和手机立即绑定

如何在networkx可视化中为不同的节点集设置不同的标签选项?

如何在networkx可视化中为不同的节点集设置不同的标签选项?

繁华开满天机 2022-10-11 21:06:50
我有一个由三组节点组成的图表 1. 服务器 2. 站 3. 用户 我想用网络内置可视化来绘制它们。在图中,我想要用户和站的标签,而不是服务器的标签。但是,这不起作用。当我尝试这个时:nx.draw_networkx_nodes(network,                    with_labels=False,                    nodelist=self.servers_idx,                    node_size=50, node_shape='s',                    pos=servers_pos,                    node_color='r')nx.draw_networkx_nodes(network, with_labels=True,                    nodelist=self.stations_idx,                    node_size=50, node_shape='^',                    pos=stations_pos,                    node_color='g')nx.draw_networkx_nodes(network, with_labels=True,                    nodelist=self.users_idx,                    node_size=10, node_shape='o',                    pos=users_pos,                    node_color='b')我得到下图:如您所见,它没有显示任何标签,但我已将with_labels变量值设置True为站点和用户,并且期望它会显示它们。奇怪的是,当我将所有设置为时with_labels,True它会显示所有标签。但是,如果我只将其中一个设置为False它不会显示其他两个(就像我将它们都设置为 False 一样)。有谁知道这里发生了什么?
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

正如 Paul Brodersen 所说,它看起来像一个 networkx 错误。但是您可以通过nx.draw_networkx_labels对用户和站点使用函数来绕过它,但对于服务器则不行:

import networkx as nx


network = nx.Graph()

network.add_nodes_from([1, 2, 3, 4, 5])


# Manually create positions and indices

servers_pos = {1: (-1, 1), 2: (1, 1)}

stations_pos = {3: (0, -1), 4: (1, 0)}

users_pos = {5: (0, 0)}

servers_idx = [1, 2]

stations_idx = [3, 4]

users_idx = [5]


# Draw nodes (exactly your code, but without `with_labels` attribute)

nx.draw_networkx_nodes(network, nodelist=[1, 2], node_size=50, node_shape='s', pos=servers_pos, node_color='r')

nx.draw_networkx_nodes(network, nodelist=[3, 4], node_size=50, node_shape='^', pos=stations_pos, node_color='g')

nx.draw_networkx_nodes(network, nodelist=[5], node_size=10, node_shape='o', pos=users_pos, node_color='b')


# Manually create labels for users and stations

stations_labels = {3: 'WAKA-3', 4: 'WAKA-4'}

users_labels = {5: 'John Doe'}

nx.draw_networkx_labels(

    network,

    pos=stations_pos,

    labels=stations_labels

)

nx.draw_networkx_labels(

    network,

    pos=users_pos,

    labels=users_labels

)

结果如下:

//img1.sycdn.imooc.com//63456a900001cff403890253.jpg

查看完整回答
反对 回复 2022-10-11
  • 1 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号