簡體   English   中英

無法 plot 與 Python 中的曲率精確相切

[英]Unable to plot an accurate tangent to a curvature in Python

我有一個曲率數據集,我需要找到曲線的切線,但不幸的是,這離曲線有點遠。 請指導我與問題相關的問題解決方案。 謝謝:我的代碼如下:

fig, ax1 = plt.subplots()
chData_m = efficient.get('Car.Road.y')  

x_fit = chData_m.timestamps
y_fit = chData_m.samples

fittedParameters = np.polyfit(x_fit[:],y_fit[:],1)

f = plt.figure(figsize=(800/100.0, 600/100.0), dpi=100)
axes = f.add_subplot(111)

    # first the raw data as a scatter plot
axes.plot(x_fit, y_fit,  'D')

    # create data for the fitted equation plot
xModel = np.linspace(min(x_fit), max(x_fit))
yModel = np.polyval(fittedParameters, xModel)

    # now the model as a line plot
axes.plot(xModel, yModel)

axes.set_xlabel('X Data') # X axis data label
axes.set_ylabel('Y Data') # Y axis data label

    # polynomial derivative from numpy
deriv = np.polyder(fittedParameters)

    # for plotting
minX = min(x_fit)
maxX = max(x_fit)

    # value of derivative (slope) at a specific X value, so
    # that a straight line tangent can be plotted at the point
    # you might place this code in a loop to animate
pointVal = 10.0 # example X value
y_value_at_point = np.polyval(fittedParameters, pointVal)
slope_at_point = np.polyval(deriv, pointVal)

ylow = (minX - pointVal) * slope_at_point + y_value_at_point
yhigh = (maxX - pointVal) * slope_at_point + y_value_at_point

    # now the tangent as a line plot
axes.plot([minX, maxX], [ylow, yhigh])

plt.show()
plt.close('all') # clean up after using pyplot

output 是: 在此處輸入圖像描述

我不確定您想如何使用 numpy polyfit/polyval來確定切線公式。 我在這里描述了一種不同的方法。 這種方法的優點是它對 function 的性質沒有任何假設。 缺點是它不適用於垂直切線。
為了安全起見,我考慮了這兩種情況,即評估的 x 值是您系列中的一個數據點,而事實並非如此。 可能會出現一些問題,因為我看到您在問題中提到了時間戳,而沒有通過提供玩具數據集來指定它們的性質 - 因此,此版本可能會或可能不會與原始數據的日期時間對象或時間戳一起使用:

import matplotlib.pyplot as plt
import numpy as np

#generate fake data with unique random x-values between 0 and 70
def func(x, a=0, b=100, c=1, n=3.5):
    return a + (b/(1+(c/x)**n))
np.random.seed(123)
x = np.random.choice(range(700000), 100)/10000
x.sort()
y = func(x, 1, 2, 15, 2.4)


#data point to evaluate
xVal = 29

#plot original data
fig, ax = plt.subplots()
ax.plot(x, y, c="blue", label="data")

#calculate gradient
slope = np.gradient(y, x)

#determine slope and intercept at xVal
ind1 = (np.abs(x - xVal)).argmin()
#case 1 the value is a data point
if xVal == x[ind1]:
    yVal, slopeVal = y[ind1], slope[ind1]    
#case 2 the value lies between to data points
#in which case we approximate linearly from the two nearest data points
else:
    if xVal < x[ind1]:
        ind1, ind2 = ind1-1, ind1
    else:
        ind1, ind2 = ind1, ind1+1         
    yVal = y[ind1] + (y[ind2]-y[ind1]) * (xVal-x[ind1]) / (x[ind2]-x[ind1])
    slopeVal = slope[ind1] + (slope[ind2]-slope[ind1]) * (xVal-x[ind1]) / (x[ind2]-x[ind1])
intercVal = yVal - slopeVal * xVal    

ax.plot([x.min(), x.max()], [slopeVal*x.min()+intercVal, slopeVal*x.max()+intercVal], color="green", 
        label=f"tangent\nat point [{xVal:.1f}, {yVal:.1f}]\nwith slope {slopeVal:.2f}\nand intercept {intercVal:.2f}" )
ax.set_ylim(0.8 * y.min(), 1.2 * y.max())
ax.legend()

plt.show()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM