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

如何用Pyplot连接两条曲线中指定索引对应的点

问题描述

我已经用以下代码绘制了两条曲线:

x = range(mov_x_1.shape[0])
plt.plot(x,mov_x_1)
plt.plot(x, mov_x_2)
plt.show()

现在我有一个变量:

path = [(0, 0), (1, 1), (2, 1), (3, 1), (4, 2), (5, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (7, 9), (8, 9), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (19, 19)]

其中每个元组的第一个元素是mov_x_1的索引,第二个是mov_x_2的索引。需要连接每对索引对应的两条曲线上的点,请问该如何实现?

实现方法

在原有绘图代码的基础上,遍历path中的每一组索引对,取出两条曲线上对应点的坐标,绘制连接这两个点的线段即可。具体代码如下:

import matplotlib.pyplot as plt

# 绘制原始两条曲线
x = range(mov_x_1.shape[0])
plt.plot(x, mov_x_1, label='Curve 1')
plt.plot(x, mov_x_2, label='Curve 2')

# 遍历索引对,绘制连接线段
for idx1, idx2 in path:
    # 获取两条曲线上目标点的坐标
    point1 = (idx1, mov_x_1[idx1])
    point2 = (idx2, mov_x_2[idx2])
    # 绘制两点间的线段
    plt.plot([point1[0], point2[0]], [point1[1], point2[1]], color='gray', linestyle='--')

# 可选:添加图表标注美化
plt.xlabel('Index')
plt.ylabel('Value')
plt.legend()

plt.show()

代码说明

  • 保留原有曲线绘制逻辑,确保基础曲线正常显示。
  • 循环处理path中的每个索引对,精准定位两条曲线上的对应点。
  • 用灰色虚线绘制连接线段,可根据需求调整color(如red、blue)和linestyle(如solid实线、:点线)参数。
  • 可选的坐标轴标签、图例能让图表更易读,可按需添加或删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:16:03