Networkx and Matplotlib: how to access node attributes and show them as annotation

Viewed 638

I'm trying to get the on hover to work for this networkx matplotlib graph, but I'm getting a key error issue. I want to create a node with the key name as a string and have that as the label. However, it looks like the on hover function that gets called breaks at the xy=pos[node] section. Here's some output of what some of that looks like:

  • obj in this output is me printing the node keys.
  • ind is me hovering over the node.
  • node is me trying to figure out the link between the node key and what hover is looking for.
pos: {'A': array([-0.88308537, -0.21952651]), 'B': array([ 0.70105714, -0.78047349]), 'C': array([0.18202824, 1.        ])}

obj: A
obj: B
obj: C
ind: {'ind': array([], dtype=int32)}
ind: {'ind': array([2], dtype=int32)}
node: 2
ind: {'ind': array([2], dtype=int32)}
node: 2
ind: {'ind': array([2], dtype=int32)}

Code below:

import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import edgelist
import numpy as np

G = nx.DiGraph()

G.add_node("A", attr1=20)
G.add_node("B", attr1=25)
G.add_node("C", attr1=30)

fig, ax = plt.subplots()
pos = nx.spring_layout(G)
print('pos:', pos)

nodes = nx.draw_networkx_nodes(G, pos, node_size=500)

for obj in G.nodes:
    print('obj:', obj)

nx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color='black')

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]
    print('node:',node)
    xy = pos[node]
    print('here:', xy)
    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)
        print('ind:',ind)
        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()

Error:

xy = pos[node]
KeyError: 2

It looks like it's trying to find a key with a number instead of a letter. That's why I'm getting a key error. But I'm not sure as to why I can't get it to accept a string instead.

1 Answers

node_index = ind["ind"][0] is an integer index in the list of nodes. Networkx stores its nodes in a dictionary, using the node name. G.nodes[2] gives an error, because G.nodes is a dictionary which is indexed by node names.

You can convert G.nodes to a list, and find the name at node_index: node_name = list(G.nodes)[node_index]. With that name, you can find the attributes: node_attr = G.nodes[node_name].

To work with hover annotations, I'd suggest the mplcursors library, which hides many of the internal bookkeeping.

Here is the updated example:

import matplotlib.pyplot as plt
import networkx as nx
import mplcursors

G = nx.DiGraph()
G.add_node("A", attr1=20)
G.add_node("B", attr1=25)
G.add_node("C", attr1=30)

fig, ax = plt.subplots()
pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G, pos, node_size=500, node_color='dodgerblue')

nx.draw_networkx_labels(G, pos, font_color='yellow')
nx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color='black')

def update_annot(sel):
    node_index = sel.target.index
    node_name = list(G.nodes)[node_index]
    node_attr = G.nodes[node_name]
    text = node_name + ' ' + '\n'.join(f'{k}: {v}' for k, v in node_attr.items())
    sel.annotation.set_text(text)

cursor = mplcursors.cursor(nodes, hover=True)
cursor.connect('add', update_annot)

plt.show()

networkx with mplcursors

Related