用列表中的重复值绘制平滑曲线 [英] Plot smooth curve with duplicate values in list

查看:308
本文介绍了用列表中的重复值绘制平滑曲线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示两个列表之间的平滑曲线.
这两个列表的值对应于另一个列表中的不同值.这两个列表的值通过它们的索引链接.当然两个列表的大小是一样的.

I would like to display the smoothed curve between two lists.
The two lists have values that they correspond to different values on the other list. The values of the two lists are linked by their indices. Of course the size of the two lists is identical.

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

list1 = [0.9117647058823529, 0.9117647058823529, 0.9090909090909091,..]
list2 = [0.32978723404255317, 0.34065934065934067, 0.3448275862068966,..]

#plt.plot(list1, list2) works well

x = np.array(list1)
y = np.array(list2)

xnew = np.linspace(x.min(), x.max(), 300) 
spl = make_interp_spline(x, y)
y_smooth = spl(xnew)
plt.plot(xnew, y_smooth)

给我 ValueError: Expect x to be a 1-D sorted array_like.

当我使用 interp1d 而不是 make_interp_spline 我有 ValueError: Expect x to not have duplicates

When I use interp1d rather than make_interp_spline I have ValueError: Expect x to not have duplicates

如何在不丢失任何点的情况下显示平滑曲线?感谢您的关注.

How to display the smoothed curve without losing any point? Thank you for your attention.

推荐答案

您可以使用一个参数(称为 param in下面的代码)从 0 到 1(或任何其他任意范围),计算插值样条的系数,然后使用更精细的参数间距再次插值曲线.

You can parameterize a curve represented by the x/y values with a parameter (called param in the code below) that goes from 0 to 1 (or any other arbitary range), compute the coefficients of the interpolating spline and then interpolate the curve again using a finer spacing of the parameter.

param = np.linspace(0, 1, x.size)
spl = make_interp_spline(param, np.c_[x,y], k=2) #(1)
xnew, y_smooth = spl(np.linspace(0, 1, x.size * 100)).T #(2)
plt.plot(xnew, y_smooth)
plt.scatter(x, y, c="r")

备注:

  1. 如果有三个以上的可用数据点,可以选择样条的阶数大于 2.默认值为 k=3.

  1. The degree of the spline can be chosen to be greater than 2 if there are more than three datapoints available. The default would be k=3.

100 控制新曲线的内插点数.如果 x 变大,这里可以使用更小的数字.

100 controls the amount of interpolated points for the new curve. If x becomes larger, a smaller number could be used here.

结果:

这篇关于用列表中的重复值绘制平滑曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆