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

如何基于NetworkX节点属性使用Bokeh为节点着色?

基于NetworkX节点属性为Bokeh节点着色的解决方案

我来帮你搞定这个问题!要基于节点属性(比如你代码里的club)给Bokeh图的节点分配填充颜色,核心是用Bokeh的分类颜色映射器(CategoricalColorMapper)——因为club是分类属性,这种映射器能完美匹配不同类别和对应颜色。

咱们来一步步调整你的代码:

步骤1:导入必要的颜色映射模块

首先要新增导入CategoricalColorMapper,它负责把节点属性的分类值映射到指定颜色:

from bokeh.models import CategoricalColorMapper

步骤2:定义颜色映射规则

根据karate_club_graph里的两个俱乐部(Mr. Hi和Officer),给每个类别分配对应的颜色:

# 定义俱乐部到颜色的映射,你可以自定义喜欢的颜色
color_mapper = CategoricalColorMapper(
    factors=['Mr. Hi', 'Officer'],
    palette=['#2ecc71', '#e74c3c']  # 绿色和红色,可替换为其他颜色码
)

步骤3:给节点渲染器绑定颜色映射

修改节点的fill_color属性,让它关联到club字段并使用上面定义的颜色映射:

graph.node_renderer.glyph = Circle(
    size=10,
    fill_color={'field': 'club', 'transform': color_mapper},
    line_color='black'  # 给节点加黑色边框,提升可读性
)

完整修改后的代码

import networkx as nx
from bokeh.io import show, output_notebook
from bokeh.plotting import figure
from bokeh.models import Circle, HoverTool, TapTool, BoxSelectTool, CategoricalColorMapper
from bokeh.models.graphs import from_networkx

output_notebook()

# 创建示例图
G = nx.karate_club_graph()

# 创建画布
plot = figure(x_range=(-1.1, 1.1), y_range=(-1.1, 1.1))

# 添加交互工具
plot.add_tools(
    HoverTool(tooltips=[("Name", "@name"), ("Club", "@club")]),
    TapTool(),
    BoxSelectTool()
)

# 从NetworkX转换为Bokeh图结构
graph = from_networkx(G, nx.spring_layout, iterations=1000, scale=1, center=(0,0))

# 给节点数据源添加属性
graph.node_renderer.data_source.data['name'] = list(G.nodes())
graph.node_renderer.data_source.data['club'] = [i[1]['club'] for i in G.nodes(data=True)]

# 设置节点样式与颜色映射
color_mapper = CategoricalColorMapper(
    factors=['Mr. Hi', 'Officer'],
    palette=['#2ecc71', '#e74c3c']
)
graph.node_renderer.glyph = Circle(
    size=10,
    fill_color={'field': 'club', 'transform': color_mapper},
    line_color='black'
)

plot.renderers.append(graph)

show(plot)

效果说明

运行修改后的代码后,你会看到属于Mr. Hi俱乐部的节点显示为绿色,Officer俱乐部的节点显示为红色(当然你可以替换palette里的颜色码来调整),同时悬停工具依然能正常显示节点的名称和俱乐部信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:38:14