Hướng dẫn how do you fit a regression line on a scatter plot in python? - làm cách nào để bạn điều chỉnh đường hồi quy trên biểu đồ phân tán trong python?

Thông thường khi bạn thực hiện hồi quy tuyến tính đơn giản, bạn có thể quan tâm đến việc tạo ra một biểu đồ phân tán để trực quan hóa các kết hợp khác nhau của các giá trị X và Y cùng với dòng hồi quy ước tính.

May mắn thay, có hai cách dễ dàng để tạo ra loại cốt truyện này trong Python. Hướng dẫn này giải thích cả hai phương thức bằng cách sử dụng dữ liệu sau:

import numpy as np #create data x = np.array([1, 1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9]) y = np.array([13, 14, 17, 12, 23, 24, 25, 25, 24, 28, 32, 33])

Phương pháp 1: Sử dụng matplotlib

Mã sau đây cho thấy cách tạo biểu đồ phân tán với dòng hồi quy ước tính cho dữ liệu này bằng Matplotlib:

import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)

Hãy thoải mái sửa đổi màu sắc của biểu đồ như bạn thích. Ví dụ, ở đây, cách thay đổi các điểm riêng lẻ thành màu xanh lá cây và dòng thành màu đỏ:

#use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')

Phương pháp 2: Sử dụng Seaborn

Bạn cũng có thể sử dụng chức năng & nbsp; regplot () & nbsp; từ thư viện trực quan trên biển để tạo ra một biểu đồ phân tán với một dòng hồi quy:regplot() function from the Seaborn visualization library to create a scatterplot with a regression line:

import seaborn as sns #create scatterplot with regression line sns.regplot(x, y, ci=None)

Lưu ý rằng & nbsp; ci = none & nbsp; bảo Seaborn ẩn các dải khoảng tin cậy trên cốt truyện. Bạn có thể chọn cho họ xem nếu bạn thích, mặc dù:ci=None tells Seaborn to hide the confidence interval bands on the plot. You can choose to show them if you’d like, though:

import seaborn as sns #create scatterplot with regression line and confidence interval lines sns.regplot(x, y)

Bạn có thể tìm thấy tài liệu đầy đủ cho hàm regplot () ở đây.regplot() function here.

Tài nguyên bổ sung

Cách thực hiện hồi quy tuyến tính đơn giản trong Python Cách tạo sơ đồ dư trong Python
How to Create a Residual Plot in Python

Tôi có hai vectơ dữ liệu và tôi đã đặt chúng vào import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)5. Bây giờ tôi muốn vượt quá âm mưu phù hợp với tuyến tính với các dữ liệu này. Làm thế nào tôi sẽ làm điều này? Tôi đã thử sử dụng import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)6 và import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)7.

tdy

30.5k11 Huy hiệu vàng62 Huy hiệu bạc60 Huy hiệu Đồng11 gold badges62 silver badges60 bronze badges

đấu vớiSep 28, 2013 at 16:05

Tunakigoldisfine

129K45 Huy hiệu vàng325 Huy hiệu bạc409 Huy hiệu đồng11 gold badges55 silver badges82 bronze badges

0

import numpy as np from numpy.polynomial.polynomial import polyfit import matplotlib.pyplot as plt # Sample data x = np.arange(10) y = 5 * x + 10 # Fit with polyfit b, m = polyfit(x, y, 1) plt.plot(x, y, '.') plt.plot(x, b + m * x, '-') plt.show()

Đã trả lời ngày 4 tháng 9 năm 2016 lúc 14:30

Bạn có thể sử dụng hướng dẫn này bởi Adarsh ​​Menon //towardsdatascience.com/linear-regression-in5 silver badges16 bronze badges

Cách này là dễ dàng nhất tôi tìm thấy và về cơ bản nó trông giống như:Sep 28, 2013 at 16:20

Đã trả lời ngày 23 tháng 3 năm 2019 lúc 10:41Greg Whittier

plnnvkvplnnvkv1 gold badge18 silver badges13 bronze badges

2

5173 Huy hiệu bạc14 Huy hiệu Đồngregplot or lmplot for this:

Tôi có hai vectơ dữ liệu và tôi đã đặt chúng vào import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)5. Bây giờ tôi muốn vượt quá âm mưu phù hợp với tuyến tính với các dữ liệu này. Làm thế nào tôi sẽ làm điều này? Tôi đã thử sử dụng import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)6 và import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)7.Nov 8, 2016 at 3:33

1

tdy

import statsmodels.api as sm import numpy as np import matplotlib.pyplot as plt X = np.random.rand(100) Y = X + np.random.rand(100)*0.1 results = sm.OLS(Y,sm.add_constant(X)).fit() print(results.summary()) plt.scatter(X,Y) X_plot = np.linspace(0,1,100) plt.plot(X_plot, X_plot * results.params[1] + results.params[0]) plt.show()

Hỏi ngày 28 tháng 9 năm 2013 lúc 16:05

Summary of Regression Results ======================================= | Dependent Variable: ['y']| | Model: OLS| | Method: Least Squares| | Date: Sat, 28 Sep 2013| | Time: 09:22:59| | # obs: 100.0| | Df residuals: 98.0| | Df model: 1.0| ============================================================================== | coefficient std. error t-statistic prob. | ------------------------------------------------------------------------------ | x1 1.007 0.008466 118.9032 0.0000 | | const 0.05165 0.005138 10.0515 0.0000 | ============================================================================== | Models stats Residual stats | ------------------------------------------------------------------------------ | R-squared: 0.9931 Durbin-Watson: 1.484 | | Adjusted R-squared: 0.9930 Omnibus: 12.16 | | F-statistic: 1.414e+04 Prob(Omnibus): 0.002294 | | Prob (F-statistic): 9.137e-108 JB: 0.6818 | | Log likelihood: 223.8 Prob(JB): 0.7111 | | AIC criterion: -443.7 Skew: -0.2064 | | BIC criterion: -438.5 Kurtosis: 2.048 | ------------------------------------------------------------------------------

Goldisfinegoldisfine

4.60211 Huy hiệu vàng55 Huy hiệu bạc82 Huy hiệu đồng13 silver badges29 bronze badges

khách thăm quanSep 28, 2013 at 16:22

6525 Huy hiệu bạc16 Huy hiệu Đồngpcoving

Đã trả lời ngày 28 tháng 9 năm 2013 lúc 16:201 gold badge20 silver badges17 bronze badges

2

Greg Whittiergref Whittier

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

2.9951 Huy hiệu vàng18 Huy hiệu bạc13 Huy hiệu đồng

Tôi thích Regplot hoặc LMplot của Seaborn vì điều này:

Đã trả lời ngày 8 tháng 11 năm 2016 lúc 3:33May 18, 2016 at 8:52

1''1''1''

25.9K32 Huy hiệu vàng136 Huy hiệu bạc198 Huy hiệu đồng32 gold badges136 silver badges198 bronze badges

2

Một cách khác để làm điều đó, sử dụng #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')5:

import matplotlib.pyplot as plt import numpy as np def scatter_plot_with_correlation_line(x, y, graph_filepath): ''' //stackoverflow.com/a/34571821/395857 x does not have to be ordered. ''' # Create scatter plot plt.scatter(x, y) # Add correlation line axes = plt.gca() m, b = np.polyfit(x, y, 1) X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100) plt.plot(X_plot, m*X_plot + b, '-') # Save figure plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight') def main(): # Data x = np.random.rand(100) y = x + np.random.rand(100)*0.1 # Plot scatter_plot_with_correlation_line(x, y, 'scatter_plot.png') if __name__ == "__main__": main() #cProfile.run('main()') # if you want to do some profiling

Đã trả lời ngày 2 tháng 1 năm 2016 lúc 23:31Jan 2, 2016 at 23:31

Mới trong matplotlib 3.3

Sử dụng #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')6 mới để vẽ #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')7 đã cho độ dốc #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')8 và chặn #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')9:#use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')6 to plot #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')7 given the slope #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')8 and intercept #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')9:

import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)0

Ví dụ về #use green as color for individual points plt.plot(x, y, 'o', color='green') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #use red as color for regression line plt.plot(x, m*x+b, color='red')6 với import seaborn as sns #create scatterplot with regression line sns.regplot(x, y, ci=None)1:

import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)1

Ở đây, phương trình là một mục nhập huyền thoại, nhưng xem cách xoay các chú thích để khớp các dòng nếu bạn muốn vẽ phương trình dọc theo dòng.

Đã trả lời ngày 3 tháng 4 lúc 7:46Apr 3 at 7:46

tdytdytdy

30.5k11 Huy hiệu vàng62 Huy hiệu bạc60 Huy hiệu Đồng11 gold badges62 silver badges60 bronze badges

import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)2

đấu với

import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)3

Tunaki

129K45 Huy hiệu vàng325 Huy hiệu bạc409 Huy hiệu đồng45 gold badges325 silver badges409 bronze badges

Đã trả lời ngày 4 tháng 9 năm 2016 lúc 14:30Sep 4, 2016 at 14:30

Bạn có thể sử dụng hướng dẫn này bởi Adarsh Menon //towardsdatascience.com/linear-regression-in

Cách này là dễ dàng nhất tôi tìm thấy và về cơ bản nó trông giống như:

import matplotlib.pyplot as plt #create basic scatterplot plt.plot(x, y, 'o') #obtain m (slope) and b(intercept) of linear regression line m, b = np.polyfit(x, y, 1) #add linear regression line to scatterplot plt.plot(x, m*x+b)4

Đã trả lời ngày 23 tháng 3 năm 2019 lúc 10:41Mar 23, 2019 at 10:41

plnnvkvplnnvkvplnnvkv

5173 Huy hiệu bạc14 Huy hiệu Đồng3 silver badges14 bronze badges

Chủ đề