networkx color based on Label clustering

Viewed 1204

I have a link base data which I did clustering label for each of them and the data look like this: the id_1 and id_2 are linked to each others and the label is the cluster number for each link.

id_1,id_2,label
0,18427,1
1,21708,1
1,22208,1
1,22171,1
1,6829,1
1,16590,1
1,20135,1
1,8894,1
1,15785,1
1,10281,1
etc..

and I use networkx library to graph the line between them.

Is there a way to color the data Nodes based on cluster label as we do in the seaborn library?

1 Answers

nx.draw has plenty of arguments that allow you to customize the generated plot. In this case you want to set a edge_color that depends on the label attribute. I've modified the labels a bit here to better illustrate the point.

To reproduce your example I've generated the graph from the edgelist as a pandas dataframe, which makes it very simple. Since I've set edge_attr=True, the label will be an attribute. We can thus save it as a dictionary using nx.get_edge_attributes.

Then we can set the edge color using edge_color=list(labels.values()) with a cmap of choice and plot the graph as follows:

import matplotlib.cm as cm
from matplotlib import pyplot as plt

G = nx.from_pandas_edgelist(df, source='id_1', target='id_2', edge_attr=True)
cmap = cm.get_cmap('viridis', max(labels.values()))
labels = nx.get_edge_attributes(G, 'label')

plt.figure(figsize=(8,6))
nx.draw(G, with_labels=True, 
        edgelist=list(labels.keys()), 
        edge_color=list(labels.values()),
        edge_cmap= plt.cm.summer, 
        node_color='lightgreen', 
        node_size=1000, width=2)

enter image description here


Set up -

s = StringIO('''
id_1,id_2,label
0,18427,1
1,21708,1
1,22208,3
1,22171,4
1,6829,1
1,16590,2
1,20135,3
1,8894,2
1,15785,2
1,10281,2
''')
df = pd.read_csv(s, delim_whitespace=False, sep=',')
Related