How to add r^2 values graph in R using ggplot2? [d

2019-06-10 03:51发布

问题:

This question already has an answer here:

  • Adding Regression Line Equation and R2 on graph 6 answers

I am new to r but am using it for a project in which I wish to represent 3 different y values with same x value on the same scatteplot including linear regression lines for each along with the value. I don't know if what I have done so far is the best but:

leafdata.long<-melt(leafdata, id="Percent.Area.Loss", measure=c("R...mean", "G.mean", "B.mean"))

ggplot(leafdata.long, aes(Percent.Area.Loss, value, color=variable))+
geom_point()+geom_smooth(method=lm, se=FALSE)+opts(title="Compiled Leaf Data")

Here's the plot that it produced: http://imgur.com/eXNFY5d

Any help with changing the x and y labels along with the legend would be appreciated also. I'm very much lost.

回答1:

The above link seems to do this way nicer. However, since I already had this done by the time I saw the post above I figured I'd post anyways.

library(plyr)
d<-data.frame(cat = sample(c("a","b","c"),100,replace=T), xval=seq_len(100), yval = rnorm(100))

r2<-ddply(d,.(cat),function(x) summary(lm(x$yval ~ x$xval))$r.squared)
names(r2)<-c("cat","r2")

g<-ggplot(d, aes(x = xval, y = yval, group = cat))+geom_point(aes(color=cat))
g<-g+geom_smooth(method="lm",aes(color=cat),se=F)

g+geom_text(data=r2,aes(color=cat, label = paste("R^2: ", r2,sep="")),parse=T,x=100,y=c(1,1.25,1.5), show_guide=F)



标签: r ggplot2