用Python Matplotlib 绘制带平滑曲线的散点图

如何用Python Matplotlib 绘制带平滑曲线的散点图,其中两组xy 数据都包含有重复值即同一个x值对应多个y值,一个y值对应多个x值,不能删除重复数据的前提下,需将所有点都体现在图上

【以下回答由 GPT 生成】

回答:

要在使用Matplotlib绘制散点图时实现平滑曲线的效果,可以使用numpy库中的polyfit函数进行多项式拟合。具体步骤如下:

  1. 导入matplotlibnumpy库。
import matplotlib.pyplot as plt
import numpy as np
  1. 准备数据,包括x和y的值。
x = [1, 1, 2, 3, 3, 4, 5, 5, 6]
y = [2, 4, 3, 5, 7, 10, 8, 10, 11]
  1. 使用polyfit函数进行多项式拟合。可以选择一阶、二阶、三阶等不同的多项式拟合。
z = np.polyfit(x, y, 1)
  1. 使用多项式系数z生成拟合函数。
p = np.poly1d(z)
  1. 生成平滑曲线的x和y值,x值可以是原始数据中的任意值。
x_smooth = np.linspace(min(x), max(x), 100)
y_smooth = p(x_smooth)
  1. 绘制原始数据的散点图和平滑曲线图。
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()


【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^