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

如何在PyVis的net.add_nodes()中批量为节点添加图片?

解决PyVis批量添加节点时图片不生效的问题

问题核心原因

你的代码未生效主要有两个关键问题:

  • 节点的shape未设置为支持图片的类型(必须是"image"或"circularImage",其他shape会忽略image参数)
  • 图片路径可能存在解析误差,或批量传参时的属性匹配细节未处理到位

可行解决方案

1. 修正批量添加代码逻辑

先确保shape参数符合图片显示要求,再优化属性列表的构造,保证每个参数列表与节点列表长度严格一致:

import pandas as pd
from pyvis import network as net

# 读取节点数据(补充你漏写的CSV读取逻辑)
got_nodes = pd.read_csv('x_y_z.csv')

g = net.Network(notebook=True, width="65%", height="1000px", heading="", cdn_resources="remote")

color_lst = ['crimson', 'red', 'magenta', 'deepskyblue', 'aqua', 'skyblue', 'lime']

# 整理所有节点属性列表
nodes = got_nodes['Group'].tolist()
labels = got_nodes['Group'].tolist()
titles = got_nodes['Group_title'].tolist()
# 根据Level映射对应颜色
color_map = [color_lst[level] for level in got_nodes['Level'].tolist()]
# 强制将shape转为支持图片的类型(如果原数据不符合要求)
shapes = got_nodes['Shape'].apply(lambda x: x if x in ['image', 'circularImage'] else 'image').tolist()
# 处理图片路径,建议用绝对路径避免层级问题
img_paths = [f'./{img}' for img in got_nodes['Image'].tolist()]

# 批量添加节点
g.add_nodes(
    nodes,
    label=labels,
    title=titles,
    color=color_map,
    shape=shapes,
    image=img_paths
)

# 生成可视化HTML文件
g.write_html('network.html')

2. 路径排查技巧

  • 若使用相对路径,确保生成的network.html与图片文件处于同一目录,或路径层级正确(比如图片在./assets/下,路径需写./assets/{img})
  • 直接使用绝对路径(如/Users/xxx/project/images/avatar.png)可彻底规避路径解析问题

备选方案:字典式批量添加

如果上述方式仍有问题,可通过遍历DataFrame构造节点字典,实现更灵活的属性配置:

# 遍历每行数据添加节点
for idx, row in got_nodes.iterrows():
    node_color = color_lst[row['Level']]
    node_shape = row['Shape'] if row['Shape'] in ['image', 'circularImage'] else 'image'
    g.add_node(
        row['Group'],
        label=row['Group'],
        title=row['Group_title'],
        color=node_color,
        shape=node_shape,
        image=f'./{row["Image"]}'
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:10:38