How to add a legend to networkx graph based on node colour

Viewed 2790

I'm using NetworkX for the first time and I'm drawing a simple network based on a pandas dataframe.

The nodes are in Nodes_df, which has the ID and corresponding Group, where the group determines what colour the node will be. The Edges_df has the edges which are the ties between ID and ID_2. All of the ids are in Nodes_df.

I can draw the graph, and colour the nodes based on a dictionary which replaces the strings (i.e. "Group1") with a number which is used by the cmap argument.

Colour_df = Edges_df.replace({"Group5": 5,"Group4": 4, "Group3": 3, "Group2": 2, "Group1": 1})

Colour_map = dict(zip(Nodes_df["ID"].astype(float), Colour_df["Group"]))

G = nx.from_pandas_edgelist(df=Edges_df, source="ID", target="ID_2",
                            create_using=nx.Graph())

values = [Colour_map.get(node) for node in G.nodes()]

nx.draw(G, cmap=plt.get_cmap('Spectral'), node_color=values,
        node_size=20)

plt.show()

I'm using matplotlib and I cannot get a legend to appear on the graph. I've tried passing the dictionary to the label argument in nx.draw_networkx_nodes() but I just get KeyError: 5.

I just want a legend that looks like:

[ ] Group1

[ ] Group2

[ ] Group3

[...]

1 Answers

You can create an empty scatter plot with the same color scheme as your graph in the same plot and use its legend:

dummy graph data

Nodes_df = pd.DataFrame(
    {'ID': range(20),
     'Group': ['Group{}'.format(np.random.randint(1,6)) for a in range(20)]}
)

Edges_df = pd.DataFrame(
    {'ID': np.random.randint(0,20,20),
     'ID_2': np.random.randint(0,20,20)}
)

Edges_df = Edges_df.merge(Nodes_df, how='left', left_on='ID', right_on='ID')

Color

# your code
Colour_df = Edges_df.replace({"Group5": 5,"Group4": 4, "Group3": 3, "Group2": 2, "Group1": 1})
Colour_map = dict(zip(Nodes_df["ID"].astype(float), Colour_df["Group"]))
G = nx.from_pandas_edgelist(df=Edges_df, source="ID", target="ID_2",
                            create_using=nx.Graph())
values = [Colour_map.get(node) for node in G.nodes()]

Drawing

# compute maximum value s.t. all colors can be normalised
maxval = np.max(values) 

# get colormap
cmap=plt.cm.Spectral

# draw graph
nx.draw(G,
        node_color = [cmap(v/maxval) for v in values], # feed normalised group numbers directly into colormap
        node_size=50)

# make empty plot with correct color and label for each group
for v in set(values):
    plt.scatter([],[], c=[cmap(v/maxval)], label='Group{}'.format(v))

plt.legend()
plt.show()

enter image description here

Related