Multiple ggplot linear regression lines

I draw the appearance of the species in multiple variables on the same plot. There are many other variables, but I just kept important for 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 managed to capture this beautiful and get it beautifully 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 value of the square R) and still no luck. Also, the axis labels refuse to change from X and Y, which I have never encountered before. Can someone help me with this? Greetings

+3
source share
1 answer

Using geom_smooth geom in ggplot2 gets regression strings for display. I am using the mtcars , which is 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 does not make any difference. Result:

enter image description here

There is a more complicated (but better looking) method to achieve the same, using the melt package from 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)") 

One of the important elements of this solution is the option scales="free_x" , which allows you to independently scale X for each facet graph.

enter image description here

+7
source

Source: https://habr.com/ru/post/1239148/


All Articles