来自 pandas 数据框的边缘列表,具有不同颜色的节点

Edgelist from pandas dataframe with nodes of different colours

我有以下数据框:

Src  Dst
A    [A,B]
B    [B,A]
C    [C]
D    [D,E,F]
E    [E,D,F]
F    [F,D,E]
...

我想生成一个网络,其中 Src 是节点,Dst 是边,新列 Weight 可以分配不同的颜色(绿色) A 或 D 的节点,而其他节点都相同(例如蓝色)。

我试过如下:

创建新列权重

nd=["A","D"]
df['Weight'] = np.where(df.Src.isin(nd), 1, 0)

问题在这里,我不知道如何分配颜色,所以我只是尝试为 A 或 D 分配值 1,为所有其他值分配 0,并分别更改颜色。

对于图表,我使用了以下内容

G = nx.from_pandas_edgelist(df, 'Src', 'Dst')

上面这行代码没有和Dst中的节点连线,无法理解原因。
我发现了一些可能有助于分配颜色的东西:

   colors=[]
for n in df.Src:
    if n in df.Weight:
        colors.append('g')
    else:
        colors.append('b')

# nodes
nx.draw_networkx_nodes(G,pos, node_color = colors)

但是我遇到了这个错误:

ValueError: 'c' argument has 79 elements, which is inconsistent with 'x' and 'y' with size 76.

下图与我的预期输出类似(AD 节点绿色,其他节点蓝色,链接基于 Dst 数据;请注意图像以下当前不会再现预期的颜色和边缘)。

你能帮我提一下如何做的建议吗?

这是一种方法:

df["color"] = "blue"
df.loc[df.Src.isin(["A", "D"]), "color"] = "green"

# The following line is needed because, at least in the way my dataset 
# is created, 'Dst' is not a list but rather a string. 
# For example, Dst of 'A' is the string "[A,B]". Here, 
# I'm converting it to the list ["A", "B"]
# If your data doesn't need this, just comment this line out. 
df["Dst"] = df.Dst.apply(lambda x: x[1:-1].split(","))

G = nx.from_pandas_edgelist(df.explode("Dst"), 'Src', 'Dst')
nx.draw(G, node_color = df.color)

输出为:

万一其他人遇到 plt.scatter 颜色与 x,y 维度不匹配的问题,您可以通过手动映射节点的颜色来解决它。我的示例是一个多图:

graph = nx.from_pandas_edgelist(df, 'source', 'target', edge_key='node_type', edge_attr=['edge_id'], 
                         create_using=nx.MultiGraph)

nodes = graph.nodes()
colors = ['blue' if node in old_nodes else 'yellow' for node in nodes]

plt.figure(figsize=(64,48))
nx.draw(graph, with_labels=True, font_weight='bold', node_color=colors)