Networkx in Python - draw node attributes as labels outside the node
You have access to the node positions in the 'pos' dictionary. So you can use matplotlib to put text wherever you like. e.g.
In [1]: import networkx as nx
In [2]: G=nx.path_graph(3)
In [3]: pos=nx.spring_layout(G)
In [4]: nx.draw(G,pos)
In [5]: x,y=pos[1]
In [6]: import matplotlib.pyplot as plt
In [7]: plt.text(x,y+0.1,s='some text', bbox=dict(facecolor='red', alpha=0.5),horizontalalignment='center')
Out[7]: <matplotlib.text.Text at 0x4f1e490>
I like to create a nudge
function that shifts the layout by an offset.
import networkx as nx
import matplotlib.pyplot as plt
def nudge(pos, x_shift, y_shift):
return {n:(x + x_shift, y + y_shift) for n,(x,y) in pos.items()}
G = nx.Graph()
G.add_edge('a','b')
G.add_edge('b','c')
G.add_edge('a','c')
pos = nx.spring_layout(G)
pos_nodes = nudge(pos, 0, 0.1) # shift the layout
fig, ax = plt.subplots(1,2,figsize=(12,6))
nx.draw_networkx(G, pos=pos, ax=ax[0]) # default labeling
nx.draw_networkx(G, pos=pos, with_labels=False, ax=ax[1]) # default nodes and edges
nx.draw_networkx_labels(G, pos=pos_nodes, ax=ax[1]) # nudged labels
ax[1].set_ylim(tuple(i*1.1 for i in ax[1].get_ylim())) # expand plot to fit labels
plt.show()
In addition to Aric's answer, the pos
dictionary contains x, y
coordinates in the values. So you can manipulate it, an example might be:
pos_higher = {}
y_off = 1 # offset on the y axis
for k, v in pos.items():
pos_higher[k] = (v[0], v[1]+y_off)
Then draw the labels with the new position:
nx.draw_networkx_labels(G, pos_higher, labels)
where G
is your graph object and labels
a list of strings.