• Home
  • How to add a legend to networkx graph based on node colour? – Python

How to add a legend to networkx graph based on node colour? – Python

You can add a legend to a NetworkX graph based on node color using Matplotlib. One way to do this is by creating a custom function that maps the nodes to the appropriate color, and then passing this function to the nodelist parameter of the nx.draw_networkx_nodes() function.

Here’s an example:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_nodes_from([1, 2, 3], color='red')
G.add_nodes_from([4, 5, 6], color='blue')

pos = nx.spring_layout(G)

def node_color(node):
return G.nodes[node]['color']

nx.draw_networkx_nodes(G, pos, nodelist=G.nodes, node_color=node_color, node_size=600)

# create a legend
red_patch = mpatches.Patch(color='red', label='Group 1')
blue_patch = mpatches.Patch(color='blue', label='Group 2')
plt.legend(handles=[red_patch, blue_patch])

plt.show()

This will create a legend that shows the different colors used for the nodes in the graph. The legend will show “Group 1” for the red nodes and “Group 2” for the blue nodes.

In this example, the node color is determined by the “color” attribute of the node. You can change this to any other attribute or function that you want to use to determine the node color.