如何用Python Matplotlib 绘制带平滑曲线的散点图,其中两组xy 数据都包含有重复值即同一个x值对应多个y值,一个y值对应多个x值,不能删除重复数据的前提下,需将所有点都体现在图上
【以下回答由 GPT 生成】
回答:
要在使用Matplotlib绘制散点图时实现平滑曲线的效果,可以使用numpy
库中的polyfit
函数进行多项式拟合。具体步骤如下:
matplotlib
和numpy
库。import matplotlib.pyplot as plt
import numpy as np
x = [1, 1, 2, 3, 3, 4, 5, 5, 6]
y = [2, 4, 3, 5, 7, 10, 8, 10, 11]
polyfit
函数进行多项式拟合。可以选择一阶、二阶、三阶等不同的多项式拟合。z = np.polyfit(x, y, 1)
p = np.poly1d(z)
x_smooth = np.linspace(min(x), max(x), 100)
y_smooth = p(x_smooth)
plt.scatter(x, y, label='Data Points')
plt.plot(x_smooth, y_smooth, label='Smoothing Curve', color='red')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot with Smoothing Curve')
plt.show()
完整代码如下:
import matplotlib.pyplot as plt
import numpy as np
x = [1, 1, 2, 3, 3, 4, 5, 5, 6]
y = [2, 4, 3, 5, 7, 10, 8, 10, 11]
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
x_smooth = np.linspace(min(x), max(x), 100)
y_smooth = p(x_smooth)
plt.scatter(x, y, label='Data Points')
plt.plot(x_smooth, y_smooth, label='Smoothing Curve', color='red')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot with Smoothing Curve')
plt.show()
【相关推荐】