问题
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