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.
