![](/img/trans.png)
[英]How to plot Month on the x-axis and Rainfall on the y-axis with Seaborn?
[英]Is there a way to get the x-axis and y-axis values of my seaborn plot?
我使用 seaborn 庫來擬合我的數據的回歸線。 然后我還繪制了殘差 plot。 我現在需要查看殘差的直方圖分布嗎? 我怎么能做到這一點,因為我沒有在圖表中繪制的值。
這是我的代碼:
fig,axes = plt.subplots(1,3,figsize=(15,5))
sns.regplot(x = 'Radio',y='Sales',data=df_advertising,ax = axes[0])
sns.residplot(x = 'Radio',y='Sales',data=df_advertising,ax = axes[1])
如何獲取我的殘差 plot 的值,以便我可以 plot 對應的直方圖查看分布。
謝謝,任何幫助將不勝感激。 我只是一個初學者。
恢復適合度或值是不太可能的(另請參閱此問題)。 你知道你適合什么也是有道理的,然后 plot 殘差。 下面我使用一個示例數據集:
import matplotlib. pyplot as plt
import seaborn as sns
import numpy as np
import statsmodels.api as sm
df_advertising = pd.DataFrame({'Radio':np.random.randint(1,10,100)})
df_advertising['Sales'] = 3*df_advertising['Radio'] + np.random.normal(10,4,100)
我們可以使用 plot 它使用 seaborn:
fig,axes = plt.subplots(1,2,figsize=(10,5))
sns.regplot(x = 'Radio',y='Sales',data=df_advertising,ax = axes[0])
sns.residplot(x = 'Radio',y='Sales',data=df_advertising,ax = axes[1])
seaborn 使用 statsmodels,所以讓我們使用它來擬合並獲得預測:
mod = sm.OLS(df_advertising['Sales'],sm.add_constant(df_advertising['Radio']))
res = mod.fit()
test = df_advertising[['Radio']].drop_duplicates().sort_values('Radio')
predictions = res.get_prediction(sm.add_constant(test))
predictions = pd.concat([test,predictions.summary_frame(alpha=0.05)],axis=1)
predictions.head()
Radio mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
13 1 11.132902 0.700578 9.742628 12.523175 3.862061 18.403742
6 2 14.480520 0.582916 13.323742 15.637298 7.250693 21.710347
2 3 17.828139 0.478925 16.877728 18.778550 10.628448 25.027829
4 4 21.175757 0.399429 20.383104 21.968411 13.995189 28.356326
10 5 24.523376 0.360990 23.807002 25.239750 17.350827 31.695924
在上面,我創建了不重復數據點的測試(因為我的是計數)。 現在我們擁有 plot 的所有內容。 殘差只是在resid
object 的殘差之下:
fig,axes = plt.subplots(1,3,figsize=(15,5))
sns.scatterplot(x='Radio',y='Sales',ax=axes[0],data=df_advertising)
axes[0].plot(predictions['Radio'], predictions['mean'], lw=2)
axes[0].fill_between(x=predictions['Radio'],
y1=predictions['mean_ci_lower'],y2=predictions['mean_ci_upper'],
facecolor='blue', alpha=0.2)
sns.scatterplot(x='Radio',y='Sales',ax=axes[1],
data=pd.DataFrame({'Radio':df_advertising['Radio'],
'Sales':res.resid})
)
axes[1].axhline(0, ls='--',color="k")
sns.distplot(res.resid,ax=axes[2],bins=20)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.