使用 networkx 可视化 k-cores

Visualization of k-cores using networkx

我想在一个漂亮的可视化中绘制图表的 k-cores,它可以说明不同的 k-cores 值(例如,https://www.researchgate.net/figure/Illustration-of-the-k-core-decomposition-Here-k-max-3_fig1_326621799)。 数据集示例如下:

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

为了识别度数至少为 k 的节点,我使用了以下代码:

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()

我正在尝试解决这个问题,例如使用 k 值的循环或根据 k 的值分配不同的颜色...

欢迎任何帮助或提示。

您是否正在寻找这样的东西:

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()