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

如何创建符合示例图的Ego-Network?现有代码需优化调整

优化后的自我中心网络实现代码

原代码的核心问题在于边的解析逻辑错误——你当前是把输入列表的每个元素和下一个元素连边,而非将输入按“两两一组”解析为边。另外,无向图加箭头没有意义,若需要箭头应使用有向图;同时布局可以调整让中心节点更突出,匹配自我中心网络的样式。

以下是修正后的代码:

import networkx as nx
import matplotlib.pyplot as plt

# 处理用户输入:按两两一组解析为边
user_input = list(map(int, input("Enter edges as space-separated pairs (e.g., 1 2 1 3 1 4): ").split()))
edges = [(user_input[i], user_input[i+1]) for i in range(0, len(user_input), 2)]
print("Parsed edges:", edges)

# 创建有向图(若不需要箭头,改为nx.Graph()即可)
G = nx.DiGraph()
G.add_edges_from(edges)

# 指定自我中心节点(这里取第一条边的起点,也可改为让用户单独输入)
ego = edges[0][0]

# 优化布局:让中心节点位于画布中心,其他节点环绕
pos = nx.circular_layout(G)
pos[ego] = (0, 0)  # 固定中心节点位置

# 绘制普通节点
nx.draw(G, pos, node_color="lavender",
        arrows=True, arrowstyle='->',
        node_size=800, with_labels=True, font_weight='bold')

# 突出显示自我中心节点
options = {"node_size": 1500, "node_color": "#ff4444"}
nx.draw_networkx_nodes(G, pos, nodelist=[ego], **options)

plt.title("Ego-Network")
plt.show()

关键改进点:

  • 正确解析边:将输入按两两一组转换为边列表,符合用户输入多条边的需求
  • 布局优化:使用环形布局并将中心节点固定在画布中心,更贴合自我中心网络的视觉效果
  • 节点突出:增大中心节点尺寸并使用醒目的颜色,强化自我中心的视觉焦点
  • 灵活切换图类型:若不需要箭头,只需将nx.DiGraph()改为nx.Graph()即可

测试时输入类似1 2 1 3 1 4 1 5的内容,就能生成中心节点连接多个外围节点的标准自我中心网络。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:28:13