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

使用netgraph绘制networkx网络图时如何按列表设置节点大小

netgraph根据列表设置对应节点大小的方法

你用的netgraph库的node_size参数支持传入字典格式,字典的键对应网络图的节点名称,值对应每个节点的尺寸,只需要把你现有的size_of_node列表和节点一一对应转为字典传入即可。

具体修改步骤:

  • 第一步:将节点和size_of_node列表的数值绑定为字典
    如果你确定size_of_node列表的顺序和triangle.nodes返回的节点顺序(a、b、c)一一对应,可以直接用zip打包生成字典:
    node_size_dict = dict(zip(triangle.nodes, size_of_node))
    
    如果顺序不确定,也可以手动构造字典避免对应错误:
    node_size_dict = {'a':3, 'b':1, 'c':4}
    
  • 第二步:将原Graph方法中固定的node_size=3替换为上面构造的字典即可

修改后的完整代码如下:

import matplotlib.pyplot as plt
import networkx as nx 
from netgraph import Graph 

triangle = nx.DiGraph([('a', 'b'), ('a', 'c'), ('b', 'a')])
size_of_node = [3, 1, 4]
edge_labels = {
    ('a', 'b') : 3,
    ('a', 'c') : 10,
    ('b', 'a') : 4
}

fig, ax1 = plt.subplots(1, figsize=(14,14))
# 构造节点大小字典
node_size_dict = dict(zip(triangle.nodes, size_of_node))

Graph(triangle, node_labels=True, edge_labels=edge_labels,
      edge_label_fontdict=dict(size=12, fontweight='bold'),
      edge_layout='curved',
      node_size=node_size_dict, edge_width=4, arrows=True, ax=ax1)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:09:00