I am unsure of a built-in way to do this, but networkx
plotting algorithm uses scatter
to set node size so you can create a set of ghost nodes using scatter that are used in the legend. (I am making up the term ghost because you don't actually see them. There may be an officially accepted term, I don't know.)
For some reason I am could not get these to work with scatter
so I am using plot
instead. (Note that the size of values in scatter
follows area while plot
follows width as discussed here so the the size of the ghost values used in plot
are the square-root of the sizes generated by networkx.draw_networkx
.
from math import sqrt
import networkx as nx
import matplotlib.pyplot as plt
# Create graph
G = nx.Graph()
N = 10 # number of nodes
for n in range(1,N + 1):
G.add_node(n, size = n * 100, pos = [0, n]) # size of node based on its number
# Draw graph
node_sizes = nx.get_node_attributes(G, 'size')
nx.draw_networkx(G, node_color = 'b', node_size = [v for v in node_sizes.values()])
# Make legend
for n in [2, 4, 6, 8]:
plt.plot([], [], 'bo', markersize = sqrt(n*100), label = f"{n}")
plt.legend(labelspacing = 5, loc='center left', bbox_to_anchor=(1, 0.5), frameon = False)
