为python networkx图中的节点添加工具提示

问题描述 投票:1回答:1

[我使用networkx.DiGraph创建了一个有向图,然后使用networkx.draw_spring(graph)对其进行了绘制,因此该图的所有节点都有一些详细信息存储在词典列表中。

如何添加“工具提示”之类的内容以在每个节点上的鼠标悬停时查看这些详细信息?如果可能的话,如何使此“工具提示”始终对所有节点可见,而不仅仅是悬停?

python matplotlib graph tooltip networkx
1个回答
1
投票

始终可见

要标记所有节点,您只需要使用annotate。像这样的东西

import matplotlib.pyplot as plt
import networkx as nx

G = nx.path_graph(5)
attrs = {0: {'attr1': 20, 'attr2': 'nothing'}, 1: {'attr2': 3}, 2: {'attr1': 42}, 3: {'attr3': 'hello'}, 4: {'attr1': 54, 'attr3': '33'}}
nx.set_node_attributes(G, attrs)
nx.draw(G)

for node in G.nodes:
    xy = pos[node]
    annot.xy = xy
    node_attr = G.nodes[node]
    text = '\n'.join(f'{k}: {v}' for k, v in G.nodes[node].items())
    text = f'node {node}\n' + text
    ax.annotate(text, xy=xy)

悬停时

这是在悬停时获取工具提示的有效示例。这基于使用标准matplotlib图here的工具提示。我使用draw_networkx_nodes而不是使用draw_spring来获取用于悬停和显示工具提示的对象。但是您可以使用spring_layout手动定义位置。

import matplotlib.pyplot as plt
import networkx as nx

G = nx.path_graph(5)
attrs = {0: {'attr1': 20, 'attr2': 'nothing'}, 1: {'attr2': 3}, 2: {'attr1': 42}, 3: {'attr3': 'hello'}, 4: {'attr1': 54, 'attr3': '33'}}
nx.set_node_attributes(G, attrs)

fig, ax = plt.subplots()
pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G, pos=pos, ax=ax)
nx.draw_networkx_edges(G, pos=pos, ax=ax)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):
    node = ind["ind"][0]
    xy = pos[node]
    annot.xy = xy
    node_attr = {'node': node}
    node_attr.update(G.nodes[node])
    text = '\n'.join(f'{k}: {v}' for k, v in node_attr.items())
    annot.set_text(text)

def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = nodes.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.