[英]How to find a Y axis value against a given X axis value in a Python plot?
I have a Python program to plot a set of integers against one for the other.我有一个 Python 程序到 plot 一组整数对一个为另一个。
import matplotlib.pyplot as plt
import numpy as np
line = plt.plot(np.array([0.119, 0.744, 2.225, 3.292]), np.array([0, 100, 400, 1000]))
plt.show()
I need to find the value of the Y axis, for the value "0.261" on the X axis.我需要找到 Y 轴的值,即 X 轴上的值“0.261”。
I tried the following我尝试了以下
xvalues = line[0].get_xdata()
yvalues = line[0].get_ydata()
indexNo = np.where(xvalues == xvalues[1])
print(yvalues[indexNo])
But in the xvalues[1]
, I need to provide the index of the value, not the exact value.但是在
xvalues[1]
中,我需要提供值的索引,而不是确切的值。 How can I solve this?我该如何解决这个问题?
You can use the numpy.interp() function to find the Y value for a given X value.您可以使用 numpy.interp() function 找到给定 X 值的 Y 值。 The function takes in three arguments: the X value you want to find the Y value for, the known X values, and the corresponding Y values.
function 包含三个 arguments:要为其查找 Y 值的 X 值、已知的 X 值以及相应的 Y 值。 It then returns the interpolated Y value.
然后它返回内插的 Y 值。 Here's an example of how you can use it in your case:
以下是如何在您的案例中使用它的示例:
y_val = np.interp(0.261, xvalues, yvalues)
print(y_val)
This will find the interpolated Y value for X=0.261 using the X and Y values from your line plot.这将使用行 plot 中的 X 和 Y 值找到 X=0.261 的内插 Y 值。
You can try to fit your xvalues
and yvalues
into a function, and then use the fitted function to find the y values for arbitrary x values:您可以尝试将
xvalues
和yvalues
到 function 中,然后使用拟合的 function 找到任意 x 值的 y 值:
# == Necessary Imports =========================================================
import scipy
from scipy.optimize import curve_fit
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# == Define Function to Fit X and Y points to ===================================
def func(x, a, b, c, offset):
return a / np.power(x, b) + c * x + offset
# == Set Initial Values for `func` Parameters ==================================
# Initial values for parameters: `a`, `b`, `c`, `offset`.
initial_parameters = np.array([1.0, 1.0, 1.0, 1.0])
# == X and Y data ==============================================================
# X and Y axes values.
x_data = np.array([0.119, 0.744, 2.225, 3.292])
y_data = np.array([0, 100, 400, 1000])
# == Find `func` Parameters ====================================================
# Curve fit `x_data` and `y_data`
fitted_parameters, pcov = curve_fit(func, x_data, y_data, initial_parameters)
# == Predict Y Values from `x_data` and `func` =================================
model_predictions = func(x_data, *fitted_parameters)
# == Solution Metrics ==========================================================
abs_error = model_predictions.round(3) - x_data
SE = np.square(abs_error) # Squared errors
MSE = np.mean(SE) # Mean squared errors
RMSE = np.sqrt(MSE) # Root Mean Squared Error
r_squared = 1.0 - (np.var(abs_error) / np.var(y_data))
print('Parameters:', fitted_parameters)
print(f'RMSE: {RMSE:.2f}')
print(f'R-squared: {r_squared:.2f}')
print(f'x = 0.261 -> y = {func(0.261, *fitted_parameters):.3f}')
# Parameters: [ 0.97721854 -5.22395811 159.66643236 -19.00031993]
# RMSE: 538.87
# R-squared: 0.01
# x = 0.261 -> y = 22.673
for x, true_y in zip(
[0.119, 0.744, 2.225, 3.292],
[0, 100, 400, 1000],
):
calc_y = func(x, *fitted_parameters)
print(f'x = {x} | true_y = {true_y:.2f} | y_pred = {calc_y:.2f}')
# x = 0.119 | true_y = 0.00 | y_pred = -0.00
# x = 0.744 | true_y = 100.00 | y_pred = 100.00
# x = 2.225 | true_y = 400.00 | y_pred = 400.00
# x = 3.292 | true_y = 1000.00 | y_pred = 1000.00
Given the fitted curve, the value for f(x=0.261)
is:给定拟合曲线,
f(x=0.261)
的值为:
func(0.261, *fitted_parameters)
# 22.673495002167353
You can also plot the fitted function with the original X and Y points:也可以用原来的X和Y点plot拟合function:
# == Graphics Output Section ===================================================
def func_scatter_plot(
x_data,
y_data,
fitted_parameters,
func,
log_scale: bool = True,
graph_width: float = 800,
graph_height: float = 600,
):
f = plt.figure(figsize=(graph_width/100, graph_height/100), dpi=100)
axes = f.add_subplot(111)
# first the raw data as a scatter plot
axes.plot(x_data, y_data, 'D')
# Create data for the fitted equation plot
x_model = np.linspace(min(x_data), max(x_data), 1000)
y_model = func(x_model, *fitted_parameters)
# now the model as a line plot
axes.plot(x_model, y_model)
axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label
# Comment this out for default linear scaling
if log_scale:
plt.xscale('log')
plt.show()
plt.close('all') # clean up after using pyplot
func_scatter_plot(x_data, y_data, fitted_parameters, func, log_scale=False)
Outputs:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.