【发布时间】:2021-09-30 19:14:13
【问题描述】:
我需要构建一个网络,其中节点(来自df1)根据来自不同数据集(df2)的标签具有一些特定的颜色。在df1 中,并非所有节点都已在df2 中分配了标签(例如,因为它们还没有被标记,所以它们当前具有 nan 值)。
下面的代码应该提供一个很好的例子来说明我的意思:
import networkx as nx
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, colors as mcolor
# Sample DataFrames
df1 = pd.DataFrame({
'Node': ['A', 'A', 'B', 'B', 'B', 'Z'],
'Edge': ['B', 'D', 'N', 'A', 'X', 'C']
})
df2 = pd.DataFrame({
'Nodes': ['A', 'B', 'C', 'D', 'N', 'S', 'X'],
'Attribute': [-1, 0, -1.5, 1, 1, 9, 0]
})
# Simplified construction of `colour_map`
uni_val = df2['Attribute'].unique()
colors = plt.cm.jet(np.linspace(0, 1, len(uni_val)))
# Map colours to_hex then zip with
mapper = dict(zip(uni_val, map(mcolor.to_hex, colors)))
color_map =df2.set_index('Nodes')['Attribute'].map(mapper).fillna('black')
G = nx.from_pandas_edgelist(df1, source='Node', target='Edge')
# Add Attribute to each node
nx.set_node_attributes(G, color_map, name="colour")
# Then draw with colours based on attribute values:
nx.draw(G,
node_color=nx.get_node_attributes(G, 'colour').values(),
with_labels=True)
plt.show()
Z 不是 df2,因为创建 df2 时只考虑了非 NA 值。
我想将黑色分配给未标记的节点,即那些不在df2 中的节点。
尝试运行上面的代码,我收到了这个错误:
ValueError: 'c' argument has 7 elements, which is inconsistent with 'x' and 'y' with size 8.
很明显,这个错误是由于缺少添加颜色黑色引起的,不包含在color_map中。 我不清楚如何解决这个问题。我希望能帮助您解决这个问题。
【问题讨论】:
标签: python pandas matplotlib networkx