如何在 matplotlib 中将其转换为平滑图形
how to convert this into a smooth graph in matplotlib
我需要把它改成平滑的线
import matplotlib.pyplot as plt
plt.plot([8.714871428, 8.618221961,8.338674976,7.904714805,6.73505356,6.08059523,5.423472376,4.785585409,3.615895343])
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.show()
我可以像Excel默认那样平滑吗?
获得平滑曲线的最简单方法可能是拟合多项式。下面是 3 次多项式拟合的示例。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 8, 1000)
x_knots = list(range(0,9))
y_knots = [
8.714871428, 8.618221961, 8.338674976,
7.904714805, 6.73505356, 6.08059523,
5.423472376, 4.785585409, 3.615895343
]
poly_deg = 3
coefs = np.polyfit(x_knots, y_knots, poly_deg)
y_poly = np.polyval(coefs, x)
plt.plot(x_knots, y_knots, "o", label="data points")
plt.plot(x, y_poly, label="polynomial fit")
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.legend()
如果你想用平滑的曲线连接点,那么你必须进行插值,而不仅仅是任何曲线拟合。最简单的方法之一是样条拟合,您可以使用 scipy.interpolate
.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.interpolate import splrep, splev
>>> y = [8.714871428, 8.618221961, 8.338674976, 7.904714805, 6.73505356, 6.08059523, 5.423472376, 4.785585409, 3.615895343]
>>> x = np.arange(len(y))
>>> tck = splrep(x, y)
>>> xnew = np.linspace(x[0], x[-1])
>>> ynew = splev(xnew, tck)
>>> plt.plot(xnew, ynew)
[<matplotlib.lines.Line2D object at 0x7f0c6dbbd090>]
>>> plt.plot(x, y, 'o')
[<matplotlib.lines.Line2D object at 0x7f0c6d8f5150>]
>>> plt.show()
我需要把它改成平滑的线
import matplotlib.pyplot as plt
plt.plot([8.714871428, 8.618221961,8.338674976,7.904714805,6.73505356,6.08059523,5.423472376,4.785585409,3.615895343])
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.show()
我可以像Excel默认那样平滑吗?
获得平滑曲线的最简单方法可能是拟合多项式。下面是 3 次多项式拟合的示例。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 8, 1000)
x_knots = list(range(0,9))
y_knots = [
8.714871428, 8.618221961, 8.338674976,
7.904714805, 6.73505356, 6.08059523,
5.423472376, 4.785585409, 3.615895343
]
poly_deg = 3
coefs = np.polyfit(x_knots, y_knots, poly_deg)
y_poly = np.polyval(coefs, x)
plt.plot(x_knots, y_knots, "o", label="data points")
plt.plot(x, y_poly, label="polynomial fit")
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.legend()
如果你想用平滑的曲线连接点,那么你必须进行插值,而不仅仅是任何曲线拟合。最简单的方法之一是样条拟合,您可以使用 scipy.interpolate
.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from scipy.interpolate import splrep, splev
>>> y = [8.714871428, 8.618221961, 8.338674976, 7.904714805, 6.73505356, 6.08059523, 5.423472376, 4.785585409, 3.615895343]
>>> x = np.arange(len(y))
>>> tck = splrep(x, y)
>>> xnew = np.linspace(x[0], x[-1])
>>> ynew = splev(xnew, tck)
>>> plt.plot(xnew, ynew)
[<matplotlib.lines.Line2D object at 0x7f0c6dbbd090>]
>>> plt.plot(x, y, 'o')
[<matplotlib.lines.Line2D object at 0x7f0c6d8f5150>]
>>> plt.show()