使用 np.polyfit 计算并绘制多项式回归生成的曲线上的切线

Compute and plot tangent lines along a curve produced by polynomial regression using np.polyfit

使用 np.polyfit 将曲线拟合到数据系列并使用 np.polyval 进行评估以绘制为:

如何计算曲线上某个点的切线,以及如何使用序列中的 x 和 y 值对沿曲线的一系列切线设置动画?

ps: 感谢 James Phillips' 解决方案,多项式曲线上的切线如下所示:

x     y
0     21.05
1     21.21
2     20.76
3     20.34
4     20.27
5     20.78
6     20.60
7     20.55
8     19.95
9     19.23
10    19.64
11    19.92
12    19.91
13    19.56
14    19.39
15    19.31
16    19.35
17    18.97
18    18.69
19    19.00
20    19.15
21    19.08
22    18.97
23    19.26
24    19.52
25    19.56
26    19.28
27    19.47
28    19.85
29    19.77

这是使用 numpy 的 polyder() 自动微分多项式的示例代码,因此您无需手动计算它 - 在开发过程中更改多项式顺序时非常方便。这会在给定的 "X" 值处绘制数据、方程式和切线,这应该足以让您入门。虽然我不知道您选择的动画技术,但我个人将图像序列保存为 PNG 文件,转换为 GIF,然后在我的 zunzun.com 网站上使用 gifsicle 制作动画以创建 3D 表面图旋转。

import numpy, matplotlib
import matplotlib.pyplot as plt

xData = numpy.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0])
yData = numpy.array([21.05, 21.21, 20.76, 20.34, 20.27, 20.78, 20.60, 20.55, 19.95, 19.23, 19.64, 19.92, 19.91, 19.56, 19.39, 19.31, 19.35, 18.97, 18.69, 19.00, 19.15, 19.08, 18.97, 19.26, 19.52, 19.56, 19.28, 19.47, 19.85, 19.77])

# polynomial curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, 3)


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

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

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = numpy.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 = numpy.polyder(fittedParameters)

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

    # 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 = 15.0 # example X value
    y_value_at_point = numpy.polyval(fittedParameters, pointVal)
    slope_at_point = numpy.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


graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)