如何使用Matplotlib按指定连接关系连接散点图中的点?
使用Matplotlib实现指定连接关系的点与连线绘制
我有一组需要绘制的点数据数组:
[[ 1. 1. 82. 177. 0. 0. -1.] [ 2. 2. 83. 177. 0. 0. 1.] [ 3. 2. 84. 177. 0. 0. 2.] [ 4. 2. 85. 177. 0. 0. 3.] [ 5. 2. 86. 178. 0. 0. 4.] [ 6. 2. 83. 177. 0. 0. 2.] [ 7. 2. 84. 177. 0. 0. 6.] [ 8. 2. 85. 177. 0. 0. 7.] [ 9. 2. 86. 176. 0. 0. 8.] [ 10. 2. 87. 175. 0. 0. 9.] [ 11. 2. 86. 174. 0. 0. 10.] [ 12. 2. 85. 174. 0. 0. 11.]]各列含义:
- 第1列:点的标识符
- 第3、4列:点的(x, y)坐标
- 最后1列:该点需要连接的目标点标识符(-1表示无连接目标)
请问能否用Matplotlib按照指定连接关系连接这些点?
当然可以实现,核心思路是先建立点标识符与坐标的映射,再遍历每个点,根据目标标识符找到对应坐标绘制连线。以下是完整可运行代码:
import matplotlib.pyplot as plt # 原始点数据 points_data = [ [1., 1., 82., 177., 0., 0., -1.], [2., 2., 83., 177., 0., 0., 1.], [3., 2., 84., 177., 0., 0., 2.], [4., 2., 85., 177., 0., 0., 3.], [5., 2., 86., 178., 0., 0., 4.], [6., 2., 83., 177., 0., 0., 2.], [7., 2., 84., 177., 0., 0., 6.], [8., 2., 85., 177., 0., 0., 7.], [9., 2., 86., 176., 0., 0., 8.], [10., 2., 87., 175., 0., 0., 9.], [11., 2., 86., 174., 0., 0., 10.], [12., 2., 85., 174., 0., 0., 11.] ] # 创建点ID到坐标的映射字典,快速查找坐标 id_to_coords = {} for point in points_data: point_id = int(point[0]) id_to_coords[point_id] = (point[2], point[3]) # 初始化画布 plt.figure(figsize=(8, 6)) # 绘制所有连线 for point in points_data: current_id = int(point[0]) target_id = int(point[-1]) # 跳过无连接目标的点 if target_id == -1: continue # 获取当前点与目标点的坐标 curr_x, curr_y = id_to_coords[current_id] tgt_x, tgt_y = id_to_coords[target_id] # 绘制线段 plt.plot([curr_x, tgt_x], [curr_y, tgt_y], 'b-', linewidth=1) # 绘制点并标注ID for point_id, (x, y) in id_to_coords.items(): # zorder确保点显示在连线之上 plt.scatter(x, y, c='r', s=50, zorder=5) # 标注点ID,偏移一点避免遮挡 plt.text(x + 0.2, y + 0.2, str(point_id), fontsize=10) # 设置可视化细节 plt.xlabel('X坐标') plt.ylabel('Y坐标') plt.title('指定连接关系的点与连线') plt.grid(True) plt.show()
关键代码说明
- 映射字典:将点ID与坐标绑定,避免反复遍历数组查找,提升效率。
- 连线绘制:遍历每个点,若存在有效目标ID,直接通过字典获取坐标并绘制线段。
- 点层控制:用
zorder参数确保点显示在连线上方,避免被遮挡。 - 标注优化:给点ID添加微小偏移,避免覆盖点本身。
内容的提问来源于stack exchange,提问作者Ludovica
相关产品推荐
相关产品推荐

