반응형
파이썬에서 산점도에 선을 과도하게 그리는 방법은 무엇입니까?
두 개의 데이터 벡터가 있으며 matplotlib.scatter()
. 이제 이러한 데이터에 대한 선형 피팅을 오버 플롯하고 싶습니다. 어떻게해야합니까? 나는 scikitlearn
및 np.scatter
.
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()
나는 scikits.statsmodels에 부분적 입니다. 다음은 예입니다.
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[0] + results.params[1])
plt.show()
유일한 까다로운 부분은 절편 항을 얻기 위해 sm.add_constant(X)
열을 추가하는 것 X
입니다.
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 |
------------------------------------------------------------------------------
나는 이것을 위해 Seaborn의 regplot 또는 lmplot 을 좋아 합니다.
최적의 선을 그리는 이 훌륭한 답변 의 한 줄 버전은 다음 과 같습니다 .
plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))
np.unique(x)
대신 사용하면 정렬되지 않았거나 중복 값이 x
있는 경우 를 처리 x
합니다.
에 대한 호출 poly1d
은 이 다른 우수한 답변m*x + b
과 같이 작성하는 대신 사용할 수 있습니다.
다른 방법은 다음을 사용하는 것입니다 axes.get_xlim()
.
import matplotlib.pyplot as plt
import numpy as np
def scatter_plot_with_correlation_line(x, y, graph_filepath):
'''
http://stackoverflow.com/a/34571821/395857
x does not have to be ordered.
'''
# 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
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])
대
plt.plot(X_plot, X_plot*results.params[1] + results.params[0])
Adarsh Menon https://towardsdatascience.com/linear-regression-in-6-lines-of-python-5e1d0cd05b8d 에서이 자습서를 사용할 수 있습니다.
이 방법은 내가 찾은 가장 쉬운 방법이며 기본적으로 다음과 같습니다.
import numpy as np
import matplotlib.pyplot as plt # To visualize
import pandas as pd # To read data
from sklearn.linear_model import LinearRegression
data = pd.read_csv('data.csv') # load data set
X = data.iloc[:, 0].values.reshape(-1, 1) # values converts it into a numpy array
Y = data.iloc[:, 1].values.reshape(-1, 1) # -1 means that calculate the dimension of rows, but have 1 column
linear_regressor = LinearRegression() # create object for the class
linear_regressor.fit(X, Y) # perform linear regression
Y_pred = linear_regressor.predict(X) # make predictions
plt.scatter(X, Y)
plt.plot(X, Y_pred, color='red')
plt.show()
참조 URL : https://stackoverflow.com/questions/19068862/how-to-overplot-a-line-on-a-scatter-plot-in-python
반응형
'program story' 카테고리의 다른 글
RVM Ruby 1.9.1 설치는 zlib를 찾을 수 없지만 런타임 및 개발 라이브러리가 있습니다. (0) | 2021.01.09 |
---|---|
Javascript 변경 날짜를 (dd / mm / yyyy) 형식으로 (0) | 2021.01.09 |
프로그래밍 방식으로 iPhone의 로케일 통화 찾기 (0) | 2021.01.09 |
부울 배열의 모든 값이 참인지 확인하는 가장 우아한 방법은 무엇입니까? (0) | 2021.01.09 |
Maven- 현재 프로젝트 및 플러그인 그룹에서 접두사 'spring-boot'에 대한 플러그인을 찾을 수 없습니다. (0) | 2021.01.09 |