Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple ggplot linear regression lines

I am plotting the occurrence of a species according to numerous variables on the same plot. There are many other variables but I've only kept the important ones for the sake of this post:

 > 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 ... 

I've managed to plot this fine and get it looking nice using (where Ee is the species in question):

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") 

However, I want to add regression lines for each of the variables (and calculate the R squared value), and have had no luck so far. Also the axes labels refuse to change from X and Y which I have never encountered before. Could anybody give me any help on this? Cheers

like image 289
user25002 Avatar asked Sep 09 '14 20:09

user25002


1 Answers

Using geom_smooth geom in ggplot2 gets regression lines to display. I am using mtcars data set as it's very similar to yours:

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)")

Also, I removed aes(y=y,x=x) from ggplot as it carries no meaning. The result:

enter image description here

There is more elaborate (but better looking) method to accomplish the same using melt from reshape2 package:

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)")

One important element of this solution is option scales="free_x" that allows independent scale of X across each facet plot.

enter image description here

like image 186
topchef Avatar answered Oct 13 '22 08:10

topchef