'How can I add a legend of node labels, stored in a dictionary, to a networkx plot?
I'm plotting a simple social network with networkx and have a dictionary of node labels, where the dictionary values are individual's names. I know how to label nodes in my network with the names, but ultimately the names will be quite long and the network quite large so a legend of sorts will be appropriate. The legend will consist of rows, each of which takes the form of a node number followed by an individual's name.
Here's a simple example:
import networkx as nx
import numpy as np
A = np.matrix([[0,1,1,0,0],[1,0,1,0,0],[1,1,0,1,1],[0,0,1,0,1],[0,0,1,1,0]])
labels_dict={0: 'Donald', 1: 'Pete', 2: 'Kamala', 3: 'Elizabeth', 4: 'Bernie'}
G = nx.from_numpy_matrix(A)
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, node_color='lightgray')
ax=plt
ax.axis('off')
fig = ax.gcf()
plt.show()
Of course, this will simply label the nodes 1, 2, 3, 4, 5.
I want the legend to appear to the right of my plot and look something like the following:
- Donald
- Pete
- Kamala
- Elizabeth
- Bernie
Solution 1:[1]
I would suggest the following, using your code above.
import networkx as nx
import numpy as np
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from secrets import token_hex
A = np.matrix([[0, 1, 1, 0, 0], [1, 0, 1, 0, 0], [ 1, 1, 0, 1, 1], [0, 0, 1, 0, 1], [0, 0, 1, 1, 0]])
labels_dict = {0: 'Donald', 1: 'Pete', 2: 'Kamala', 3: 'Elizabeth', 4: 'Bernie'}
G = nx.from_numpy_matrix(A)
# plotting with the same colors for all node labels
handles_dict = {patches.Patch(color='white', label=f"{k}, {v}") for k,v in labels_dict.items()}
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, node_color='lightgray')
plt.legend(handles=handles_dict)
plt.show()
The code above would get us the following plot
If however, you want it to take different colours, you can do:
pos = nx.spring_layout(G)
# token_hex() generates random hex color/numbers
handles___ = {k: f"#{token_hex(4)}" for k in labels_dict.keys()}
handles___ = dict(sorted(handles___.items()))
handles_dict = {patches.Patch(color=k, label=v) for k, v in zip(handles___.values(), labels_dict.values())}
node_color = list(handles___.values())
nx.draw_networkx(G, pos, node_color=node_color)
plt.legend(handles=handles_dict)
plt.show()
This code will output:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | odunayo12 |


