如何从Matplotlib绘制的曲线中提取并绘制非给定x对应的y值?
嘿,这个需求其实挺常见的——你手里的曲线是离散的(x,y)点组成的,要拿到非原始采样点的y值,核心就是插值。下面给你一步步拆解解决方案,附完整代码:
解决方法:插值计算+可视化标注
1. 核心思路:用插值估算非采样点的y值
因为你的原始数据是一系列离散的点,没有x=0.23对应的记录,所以我们需要通过相邻的已知点来估算这个位置的y值。最常用的两种方式是线性插值(简单高效,适合大多数场景)和三次样条插值(生成平滑曲线,适合有连续趋势的数据)。
2. 线性插值实现(基础方案)
我们可以直接用numpy自带的interp()函数来完成线性插值,然后用matplotlib把这个点标注在曲线上:
import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111) x1 = [0.1,0.12,0.13,0.18,0.2,0.25,0.27,0.29] y1 = [1,2,3,4,5,6,7,8] ax.plot(x1, y1, color='lightblue',linewidth=3) # 定义目标x值 target_x = 0.23 # 线性插值计算对应的y值 target_y = np.interp(target_x, x1, y1) print(f"x={target_x}对应的线性插值y值:{target_y}") # 在曲线上标注这个点:红色圆点,提高层级避免被曲线遮挡 ax.scatter(target_x, target_y, color='red', s=100, zorder=5) # 添加文本标注,稍微偏移位置避免遮挡点 ax.text(target_x + 0.005, target_y, f'({target_x}, {target_y:.2f})', fontsize=10) plt.show()
3. 三次样条插值实现(平滑方案)
如果你的数据本身有连续的趋势,想要更精准的平滑插值结果,可以用scipy的interp1d函数实现三次样条插值:
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import interp1d fig = plt.figure() ax = fig.add_subplot(111) x1 = [0.1,0.12,0.13,0.18,0.2,0.25,0.27,0.29] y1 = [1,2,3,4,5,6,7,8] ax.plot(x1, y1, color='lightblue',linewidth=3) target_x = 0.23 # 创建三次样条插值函数 spline_func = interp1d(x1, y1, kind='cubic') # 计算目标y值 target_y_spline = spline_func(target_x) print(f"x={target_x}对应的三次样条插值y值:{target_y_spline:.2f}") # 标注点:用橙色区分线性插值的点 ax.scatter(target_x, target_y_spline, color='orange', s=100, zorder=5) ax.text(target_x + 0.005, target_y_spline, f'三次样条: ({target_x}, {target_y_spline:.2f})', fontsize=10) plt.show()
小提示
- 线性插值是用相邻两个点的直线段来估算数值,计算快、结果直观;
- 三次样条插值会生成一条平滑的曲线穿过所有原始点,插值结果更贴合数据的连续趋势,但需要额外安装
scipy库(pip install scipy)。
内容的提问来源于stack exchange,提问作者user3650827
相关产品推荐
相关产品推荐

