regression equations for facets

461 views
Skip to first unread message

Trong Trinh Quoc

unread,
May 1, 2012, 5:46:26 AM5/1/12
to ggp...@googlegroups.com
Dear All,

My example codes:

DF <- data.frame(group = factor(rep(1:3, each = 100)),
                 weight = c(rnorm(100, 50, 30), rnorm(100, 75, 45),
                            rnorm(100, 60, 25)),
length = c(rnorm(50, 30, 15), rnorm(50, 20, 10),
rnorm(50, 15, 5)))
library('ggplot2')

ggplot(DF, aes(length, weight)) +
facet_wrap(~group, ncol=1) +
geom_point(shape = 1) +
geom_smooth(method=lm,
se=F,
color="RED",
linetype=1,
size=1) +
opts(strip.text.x = theme_text(size = 10, angle = 0))

produces:

Inline image 1
I'd like to add regression equation for each group (1, 2 and 3) (please see example attached) in each corresponding facet, but failed. 

As always, any suggestion would be much appreciated!

Cheers Trong.
 
image.png
Untitled-1.jpg

Ben Bond-Lamberty

unread,
May 1, 2012, 6:23:16 AM5/1/12
to ggp...@googlegroups.com
>I'd like to add regression equation for each group (1, 2 and 3) (please see example attached) in each corresponding facet, but failed.

Hi Trong, try something like this:

eqnfunc <- function(d) { # function to fit models and build text equations
m <- lm(weight~length,data=d)
c(eqn=paste( "y=",round(m$coefficients[1],1),"+",round(m$coefficients[2],1),"x",sep=""))
}
library(plyr)
labeldata <- ddply(DF,.(group),eqnfunc )  # create data frame with
equation for each group

At this point you can just add, to your original qplot call,

+ geom_text(data=labeldata,aes(x=5,y=2,label=eqn),fontface="Italic")

...which puts the correct model equation in every panel.

Regards,

Ben




On Tue, May 1, 2012 at 5:46 AM, Trong Trinh Quoc <tro...@gmail.com> wrote:
>
> Dear All,
>
> My example codes:
>
> DF <- data.frame(group = factor(rep(1:3, each = 100)),
>                  weight = c(rnorm(100, 50, 30), rnorm(100, 75, 45),
>                             rnorm(100, 60, 25)),
> length = c(rnorm(50, 30, 15), rnorm(50, 20, 10),
> rnorm(50, 15, 5)))
> library('ggplot2')
>
> ggplot(DF, aes(length, weight)) +
> facet_wrap(~group, ncol=1) +
> geom_point(shape = 1) +
> geom_smooth(method=lm,
> se=F,
> color="RED",
> linetype=1,
> size=1) +
> opts(strip.text.x = theme_text(size = 10, angle = 0))
>
> produces:
>
>

Trong Trinh Quoc

unread,
May 1, 2012, 7:31:30 AM5/1/12
to Ben Bond-Lamberty, ggp...@googlegroups.com
Dear Ben,

Many thanks! Works nicely!

Cheers Trong.

--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility

To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

Reply all
Reply to author
Forward
0 new messages