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

如何为Bokeh绘制的NetworkX网络图添加边标签与边属性

解决方法

你可以根据需求选择以下两种常用的边属性展示方案,代码直接添加到你现有代码中show(plot)之前的位置即可:

方案1:边悬停显示属性(推荐,不会遮挡图面)

鼠标移动到对应边上时自动弹出属性框,适合属性内容较多的场景:

from bokeh.models import HoverTool

# 取出边渲染器的数据源
edge_ds = network_graph.edge_renderer.data_source
edge_emails = []
edge_phones = []
edge_vins = []

# 遍历补全边属性,兼容边顺序相反的情况
for start, end in zip(edge_ds.data['start'], edge_ds.data['end']):
    edge_attr = d.get((start, end), d.get((end, start), {}))
    edge_emails.append(edge_attr.get('Email', '-'))
    edge_phones.append(edge_attr.get('Phone', '-'))
    edge_vins.append(edge_attr.get('VIN', '-'))

# 将属性添加到边数据源
edge_ds.data['email'] = edge_emails
edge_ds.data['phone'] = edge_phones
edge_ds.data['vin'] = edge_vins

# 新增边专属悬停工具
edge_hover = HoverTool(
    tooltips=[
        ("关联邮箱", "@email"),
        ("关联手机号", "@phone"),
        ("关联VIN", "@vin"),
    ],
    mode='mouse',
    renderers=[network_graph.edge_renderer]
)
plot.add_tools(edge_hover)

方案2:边中点直接显示静态标签

如果需要属性默认固定展示在图上,可以用该方案:

# 读取所有节点的坐标映射
node_layout = network_graph.layout_provider.graph_layout
edge_x = []
edge_y = []
edge_text = []

# 遍历边计算中点坐标、拼接标签文本
for (u, v), attr in d.items():
    x1, y1 = node_layout[u]
    x2, y2 = node_layout[v]
    # 计算边中点坐标
    mid_x = (x1 + x2) / 2
    mid_y = (y1 + y2) / 2
    # 按需拼接标签内容
    text_parts = []
    if 'Email' in attr:
        text_parts.append(f"邮箱:{attr['Email']}")
    if 'Phone' in attr:
        text_parts.append(f"手机号:{attr['Phone']}")
    if 'VIN' in attr:
        text_parts.append(f"VIN:{attr['VIN']}")
    edge_text.append("\n".join(text_parts))
    edge_x.append(mid_x)
    edge_y.append(mid_y)

# 构造边标签数据源并渲染
edge_label_source = ColumnDataSource(dict(x=edge_x, y=edge_y, text=edge_text))
edge_labels = LabelSet(
    x='x', y='y', text='text', source=edge_label_source,
    text_font_size='8px', background_fill_color='white',
    background_fill_alpha=0.8, text_align='center'
)
plot.renderers.append(edge_labels)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:12:02