【问题标题】:How to draw cubic spline in matplotlib如何在 matplotlib 中绘制三次样条曲线
【发布时间】:2022-05-07 09:49:57
【问题描述】:

我想用平滑线连接下面的points,比如三次样条

points = [(3.28,0.00),(4.00,0.50),(4.40,1.0),(4.60,1.52),(5.00,2.5),(5.00,3.34),(4.70,3.8)]
points = points + [(4.50,3.96),(4.20,4.0),(3.70,3.90),(3.00,3.5),(2.00,2.9)]

最后得到这样的橙色线(这是使用矢量绘图语言 Asymptote 创建的)

我想知道如何在 matplotlib 中以简单的方式做到这一点。我已经看过类似的问题,例如Generating smooth line graph using matplotlib,但直接使用该方法会产生这样的图形

这当然不是我想要的。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您需要采用参数化方法,如下所示:

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

points = [(3.28,0.00),(4.00,0.50),(4.40,1.0),(4.60,1.52),(5.00,2.5),(5.00,3.34),(4.70,3.8)]
points = points + [(4.50,3.96),(4.20,4.0),(3.70,3.90),(3.00,3.5),(2.00,2.9)]
data = np.array(points)

tck,u = interpolate.splprep(data.transpose(), s=0)
unew = np.arange(0, 1.01, 0.01)
out = interpolate.splev(unew, tck)

plt.figure()
plt.plot(out[0], out[1], color='orange')
plt.plot(data[:,0], data[:,1], 'ob')
plt.show()

这基本上只是从here 部分的最后一个示例中重新设计的。

【讨论】:

  • 非常感谢!这正是我所需要的。
  • @tom10 我喜欢你的方法。你发布它的速度比我快一点。
【解决方案2】:

这几乎是循环示例here

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

def annotate_points(ax, A, B):
    for xy in zip(A, B):
        ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='offset points')

points = [(3.28,0.00),(4.00,0.50),(4.40,1.0),(4.60,1.52),(5.00,2.5),(5.00,3.34),(4.70,3.8)]
points = points + [(4.50,3.96),(4.20,4.0),(3.70,3.90),(3.00,3.5),(2.00,2.9)]
x, y = zip(*points)

fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(x, y, color='black')
annotate_points(ax, x, y)

tck,u = interpolate.splprep([x, y], s=0)
unew = np.arange(0, 1.01, 0.01)
out = interpolate.splev(unew, tck)

plt.plot(x, y, 'orange', out[0], out[1])
plt.legend(['connect the dots', 'cubic spline'])

plt.show()

【讨论】:

  • @KevinPowell 酷。在回答您的问题时,我学会了如何“解压缩”元组列表。
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2012-04-21
  • 2021-07-03
  • 2023-03-28
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
相关资源
最近更新 更多