ggplot2添加回归线(逻辑)

时间:2016-12-17 17:36:49

标签: r ggplot2

我有两行不同的代码:

ggplot(mpg,aes(displ,hwy,colour = factor(cyl))) + geom_point() + geom_smooth(method = 'lm')

ggplot(mpg,aes(displ,hwy)) + geom_point(aes(colour = factor(cyl))) + geom_smooth(method = 'lm')

第一个代码为3个不同的组生成3条回归线(因子变量) 。第二个代码只为整个数据集生成一行。

我的问题是:这种差异背后的逻辑是什么?我知道,输出取决于colour = factor(cyl),但在这种情况下你能解释一下ggplo2的逻辑吗?

1 个答案:

答案 0 :(得分:1)

考虑以下两行相同的代码(在第一种情况下,我们通过在ggplot中全局提供颜色变量来对geom_point和geom_smooth进行分组,在第二种情况下,在本地提供两者 geom_point和geom_smooth):

ggplot(mpg,aes(displ,hwy,colour = factor(cyl))) + 
geom_point() + 
geom_smooth(method = 'lm')

ggplot(mpg,aes(displ,hwy)) + 
geom_point(aes(colour = factor(cyl))) + 
geom_smooth(aes(colour = factor(cyl)), method = 'lm')

enter image description here

现在您提供的另一个示例代码,您可以通过将它们与cyl变量分组来为不同颜色的点着色,但是您不要将geom_smooth分组,这就是为什么它适合整个数据而不是像以前的情况一样分别适合3组

ggplot(mpg,aes(displ,hwy)) + 
geom_point(aes(colour = factor(cyl))) + 
geom_smooth(method = 'lm')

enter image description here