Seaborn : linear regression on top of a boxplot

自作多情 提交于 2021-02-11 08:46:19

问题


With seaborn, how I can use sns.boxplot and sns.lmplot to obtain a boxplot with a regression line from the same data ? This does not work :

tips = sns.load_dataset("tips")
ax = sns.boxplot(x="size", y="tip", data=df)
ax = sns.lmplot(x="size", y="tip", data=tips, x_estimator=np.mean); 

回答1:


You could try the following:

tips = sns.load_dataset("tips")
ax = sns.boxplot(x="size", y="tip", data=df)
ax = sns.regplot(x="size", y="tip", data=tips); 
plt.show()

Instead of using lmplot you can use regplot to create the regression line.

One thing to note here is that I see that you are using different data for each plot, so even though I don't know what kind of data you have in tips, you could try and use df instead of tips since using different datasets could give you different results.




回答2:


Use sns.regplot() instead, it's a figure-level function that lets both plots be placed in the same figure.

The code below will give you a boxplot with regression line over it. It also removes the scatter from the regression. You can change the order of the regression as you see fit. This will work when the boxplot and regplot are using the same data. If you are defining another dataset, df, then please clarify in your question and I'll update this answer.

tips = sns.load_dataset("tips")

fig, ax = plt.subplots()
sns.boxplot(x="size", y="tip", data=tips, ax=ax)
sns.regplot(x="size", y="tip", data=tips, ax=ax, scatter=False)

plt.show()



来源:https://stackoverflow.com/questions/51825223/seaborn-linear-regression-on-top-of-a-boxplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!