Visualization of k-cores using networkx

Viewed 234

I would like to plot the k-cores of a graph in a nice visualization which can illustrate the different k-core values (for instance, https://www.researchgate.net/figure/Illustration-of-the-k-core-decomposition-Here-k-max-3_fig1_326621799). A sample of dataset is the following:

Node Target Label
A      F      1
A      B      1
A      N      1
B      A      0
B      F      0 
C      F      1
A      V      1
D      S      0
D      E      0
F      A      1
F      B      1
F      G      1
G      E      0
E      W      0

To identify the nodes with at least degree k I am using the following piece of code:

G = nx.from_pandas_edgelist(df, 'Node', 'Target')

kcore=nx.k_core(G)

plt.subplot(121)
plt.title('Full')
nx.draw(G,with_labels=True)


plt.subplot(122)
plt.title('Main')
nx.draw(kcore,with_labels=True)

plt.show()

I'm trying to figure it out, for example using a loop across k values or assigning different colors depending on the value of k...

Any help or tips would be welcome.

1 Answers

Are you looking for something like this:

import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
from collections import defaultdict

# create dataframe
# df = ...

# build graph
G = nx.from_pandas_edgelist(df, 'Node', 'Target')

# build a dictionary of k-level with the list of nodes
kcores = defaultdict(list)
for n, k in nx.core_number(G).items():
    kcores[k].append(n)

# compute position of each node with shell layout
pos = nx.layout.shell_layout(G, list(kcores.values()))
colors = {1: 'red', 2: 'green'}  # need to be improved, for demo

# draw nodes, edges and labels
for kcore, nodes in kcores.items():
    nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_color=colors[kcore])
nx.draw_networkx_edges(G, pos, width=0.2)
nx.draw_networkx_labels(G, pos)
plt.show()

networkx

Related