gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:12:48 25 4
gpt4 key购买 nike

我有一个由三组节点组成的图 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')

我得到下图:

image

如您所见,没有显示任何标签,但我设置了 with_labels变量值为 True对于电台和用户,期望它会向他们展示。奇怪的是,当我设置所有 with_labelsTrue它将显示所有标签。但是如果我只将其中一个设置为 False它不会显示其他两个(就像我将它们全部设置为 False)。有谁知道这里发生了什么?

最佳答案

正如 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
)

结果如下:

enter image description here

关于python - 如何在networkx可视化中为不同的节点集设置不同的标签选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61240519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com