You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NetworkX网络中按属性条件为特定节点着色的实现方案咨询

实现方法

首先提前导入依赖库:

import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm

首先完成节点属性绑定:假设你的账户时间数据集存储为df_time,先将时间属性绑定到图节点上:

# 构建账户到time的映射字典
time_dict = df_time.set_index('Account')['Time'].to_dict()
# 给图节点添加time属性
nx.set_node_attributes(G, time_dict, name='time')

方案1:单张图按开户时间为节点着色

# 配置参数
default_color = '#808080' # 无time值/不在目标列表的节点默认灰色
# 可根据你的time实际范围调整colormap,样例中time取值为1-4的离散值
cmap = cm.get_cmap('viridis', 4)
max_time = 4
min_time = 1

# 生成节点颜色列表
node_colors = []
for node in G.nodes():
    time_val = G.nodes[node].get('time', None)
    # 匹配到有效time值则使用对应映射色
    if pd.notna(time_val) and time_val is not None:
        node_colors.append(cmap(int(time_val) - min_time))
    else:
        node_colors.append(default_color)

# 绘制网络图
plt.figure(figsize=(10,8))
# 固定随机种子保证布局可复现
pos = nx.spring_layout(G, seed=42)
nx.draw(
    G, pos=pos,
    node_color=node_colors,
    node_size=500,
    with_labels=True,
    font_size=8
)
# 添加时间色条图例
sm = cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=min_time, vmax=max_time))
sm.set_array([])
plt.colorbar(sm, label='开户时间Time')
plt.show()

如果你的time为连续值,直接删除离散cmap的数量参数,将time_val直接做归一化处理即可匹配颜色


方案2:分不同时间维度绘制多张可视化图

可以选择两种展示逻辑:全量节点仅高亮当前时间节点、仅展示到当前时间为止已开户的节点子图

逻辑1:全量节点+高亮当前时间节点

# 固定全局布局,保证多张图结构一致方便对比
pos = nx.spring_layout(G, seed=42)
# 取所有有效time值排序
time_list = sorted(df_time['Time'].dropna().unique())

for t in time_list:
    plt.figure(figsize=(8,6))
    node_colors = []
    for node in G.nodes():
        node_time = G.nodes[node].get('time', None)
        # 当前时间的节点标红,其余标灰
        if pd.notna(node_time) and node_time == t:
            node_colors.append('#FF0000')
        else:
            node_colors.append('#808080')
    nx.draw(
        G, pos=pos,
        node_color=node_colors,
        node_size=500,
        with_labels=True
    )
    plt.title(f'开户时间为{t}的账户高亮')
    plt.show()

逻辑2:仅展示到当前时间为止的子图

pos = nx.spring_layout(G, seed=42)
time_list = sorted(df_time['Time'].dropna().unique())

for t in time_list:
    plt.figure(figsize=(8,6))
    # 筛选出time<=t的节点,构建子图
    valid_nodes = [
        n for n in G.nodes() 
        if pd.notna(G.nodes[n].get('time', None)) and G.nodes[n]['time'] <= t
    ]
    sub_G = G.subgraph(valid_nodes)
    # 子图内节点按time着色,逻辑同方案1
    node_colors = [cmap(int(G.nodes[n]['time'])-1) for n in sub_G.nodes()]
    nx.draw(
        sub_G, pos=pos,
        node_color=node_colors,
        node_size=500,
        with_labels=True
    )
    plt.title(f'截止开户时间{t}的网络子图')
    plt.show()

注意事项

  • 需保证边数据集、时间数据集的Account字段类型完全一致,避免数值型/字符串型不匹配导致属性绑定失败
  • 可根据你的节点数量调整node_size、font_size参数提升可视化清晰度

内容的提问来源于stack exchange,提问作者V_sqrt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:54:09