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

Networkx绘制图时如何在同一张图显示节点属性且避免标签重叠

解决方案

你可以通过调整标签位置或者合并标签的方式解决重叠问题,以下是两种可直接复用的实现方案:

方法1:给不同标签设置位置偏移

对两个属性的标签分别做上下偏移,让名称和类型分别显示在节点的上下两侧:

import networkx as nx
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))
pos = nx.spring_layout(graph, k=5)
# 先绘制节点和边,关闭默认标签
nx.draw(graph, pos, ax=ax, edge_color=edge_color, with_labels=False)

# 提取节点属性
names = nx.get_node_attributes(graph, 'Name')
types = nx.get_node_attributes(graph, 'Type')

# 名称标签向上偏移0.1单位(偏移量可根据画布尺寸调整)
pos_name = {node: (coord[0], coord[1] + 0.1) for node, coord in pos.items()}
nx.draw_networkx_labels(graph, pos_name, labels=names, ax=ax, font_color='#1f77b4')

# 类型标签向下偏移0.1单位
pos_type = {node: (coord[0], coord[1] - 0.1) for node, coord in pos.items()}
nx.draw_networkx_labels(graph, pos_type, labels=types, ax=ax, font_color='#ff7f0e', font_size=9)

plt.show()

方法2:合并为多行单个标签

将两个属性拼接为带换行的单个标签,一次性完成绘制:

fig, ax = plt.subplots(figsize=(10,10))
pos = nx.spring_layout(graph, k=5)
nx.draw(graph, pos, ax=ax, edge_color=edge_color, with_labels=False)

# 构造合并后的多行标签
merged_labels = {}
for node in graph.nodes:
    merged_labels[node] = f"{graph.nodes[node]['Name']}\n{graph.nodes[node]['Type']}"

# 绘制多行标签
nx.draw_networkx_labels(graph, pos, labels=merged_labels, ax=ax, font_size=9)
plt.show()

额外优化技巧

  • 如果整体布局拥挤,可适当调大spring_layout的k参数,增加节点之间的间距
  • 标签过多时可缩小font_size参数,减少标签占用的空间
  • 节点数量极多的场景可以引入adjustText库自动调整文本位置,进一步避免重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:10