How to overplot a line on a scatter plot in python?

前端 未结 7 1947
轻奢々
轻奢々 2020-11-28 02:18

I have two vectors of data and I\'ve put them into matplotlib.scatter(). Now I\'d like to over plot a linear fit to these data. How would I do this? I\'ve tried

7条回答
  •  余生分开走
    2020-11-28 03:03

    A one-line version of this excellent answer to plot the line of best fit is:

    plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
    

    Using np.unique(x) instead of x handles the case where x isn't sorted or has duplicate values.

    The call to poly1d is an alternative to writing out m*x + b like in this other excellent answer.

提交回复
热议问题