多个ggplot线性回归线

时间:2014-09-09 20:16:23

标签: r ggplot2 regression

我正根据同一地块上的众多变量绘制物种的出现。还有很多其他变量,但我只是为了这篇文章而保留了重要的变量:

 > str(GH) 
 'data.frame':  288 obs. of  21 variables: 
 $ Ee       : int  2 2 1 7 6 3 0 9 3 7 ... 
 $ height   : num  14 25.5 25 21.5 18.5 36 18 31.5 28.5 19 ... 
 $ legumes  : num  0 0 55 30 0 0 55 10 30 0 ... 
 $ grass    : num  60 50 30 35 40 35 40 40 35 30 ... 
 $ forbs    : num  40 70 40 50 65 70 40 65 70 70 ... 

我已经设法将其绘制得很好并且看起来很好看(Ee是有问题的物种):

ggplot(data=GH,aes(y=y,x=x),ylab="Number of individuals (N)",xlab="Percentage cover (%); OR  Height(cm))+
geom_jitter(aes(legumes,Ee),colour="blue")+ 
geom_jitter(aes(grass,Ee),colour="green")+ 
geom_jitter(aes(forbs,Ee),colour="red")+ 
geom_jitter(aes(height,Ee),colour="black") 

但是,我想为每个变量添加回归线(并计算R平方值),到目前为止还没有运气。轴标签也拒绝改变我以前从未遇到过的X和Y.有人可以给我任何帮助吗?干杯

1 个答案:

答案 0 :(得分:8)

在ggplot2中使用geom_smooth geom可以显示回归线。我正在使用mtcars数据集,因为它与您的非常相似:

ggplot(mtcars) + 
  geom_jitter(aes(disp,mpg), colour="blue") + geom_smooth(aes(disp,mpg), method=lm, se=FALSE) +
  geom_jitter(aes(hp,mpg), colour="green") + geom_smooth(aes(hp,mpg), method=lm, se=FALSE) +
  geom_jitter(aes(qsec,mpg), colour="red") + geom_smooth(aes(qsec,mpg), method=lm, se=FALSE) +
  labs(x = "Percentage cover (%)", y = "Number of individuals (N)")

此外,我从aes(y=y,x=x)删除了ggplot,因为它没有任何意义。结果:

enter image description here

使用melt包中的reshape2来完成同样的工作还有更精细(但更好看)的方法:

require(ggplot2)
require(reshape2)
mtcars2 = melt(mtcars, id.vars='mpg')
ggplot(mtcars2) +
  geom_jitter(aes(value,mpg, colour=variable),) + geom_smooth(aes(value,mpg, colour=variable), method=lm, se=FALSE) +
  facet_wrap(~variable, scales="free_x") +
  labs(x = "Percentage cover (%)", y = "Number of individuals (N)")

此解决方案的一个重要元素是选项scales="free_x",允许在每个方面图上独立缩放X.

enter image description here

相关问题