如何从Matplotlib子图绘制的线条对象中获取未传入的数据值
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.interpwill 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
linestyleor plotting method), adjust the interpolation kind to match your setup.
内容的提问来源于stack exchange,提问作者Jamie Parker

