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

如何从Matplotlib子图绘制的线条对象中获取未传入的数据值

How to Get Interpolated Y-Values from a Matplotlib Line Object

Great question! When you create a line plot in Matplotlib, the Line2D object (your line variable here) only stores the original x and y data you passed in—it doesn’t keep the full set of interpolated points that get drawn on the figure. But you can easily calculate the y-value for an intermediate x (like x=10 in your example) by running interpolation on the original data extracted from the line.

Here's how to do it step by step:

1. Extract the original data from the line object

First, grab the raw x and y arrays you used to create the line using the get_data() method:

x_orig, y_orig = line.get_data()

2. Calculate the interpolated y-value

Matplotlib uses linear interpolation by default to connect data points in a line plot. To match this behavior, use NumPy's np.interp() function—it performs linear interpolation between points, giving you the exact y-value that matches what’s drawn on your figure:

import numpy as np

# Target x-value you want to get the y-value for
target_x = 10

# Linear interpolation (matches Matplotlib's default line rendering)
target_y = np.interp(target_x, x_orig, y_orig)

print(f"Y-value at x={target_x}: {target_y}")

If you need a smoother, non-linear interpolation (like cubic splines), use SciPy's interp1d function instead:

from scipy.interpolate import interp1d

# Create a cubic spline interpolation function
interpolator = interp1d(x_orig, y_orig, kind='cubic')

# Get the interpolated y-value
target_y_cubic = interpolator(target_x)

print(f"Cubic interpolated Y-value at x={target_x}: {target_y_cubic}")

Key Notes:

  • The linear interpolation from np.interp will always match the y-value you’d see if you looked at x=10 on your Matplotlib figure.
  • If you’ve customized the line’s interpolation behavior (e.g., using a non-standard linestyle or plotting method), adjust the interpolation kind to match your setup.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:12:39