Reference line in all plots of facet wrap

74 views
Skip to first unread message

Agustin Lobo

unread,
Sep 18, 2012, 1:24:38 AM9/18/12
to ggp...@googlegroups.com
Hi!
I'm doing
qplot(temperature,DN,color=Image,group=Image,data=vthcal1MIDAScal1m,geom=c("point","smooth"),method="lm")+
facet_wrap(~Image,ncol=2)
using data in
http://dl.dropbox.com/u/3180464/vthcal1MIDAScal1m.rda

I'm happy with the plot except that I would like to have the red line
of the first plot (M052) in all the rest of plots also (keeping it in
red, for example), to act as a reference.
But do not find the way of doing it. I'd appreciate any help on this.

Thanks,

Agus

Dennis Murphy

unread,
Sep 18, 2012, 4:23:53 AM9/18/12
to Agusti...@ictja.csic.es, ggp...@googlegroups.com
Hi:

The function ggplot_build() is one way to grab information like this from a plot, but in the future, this will probably be controlled by the gtable package if it is not already. The group mapping was unnecessary so I removed it.

p <- qplot(temperature, DN, color=Image, data=vthcal1MIDAScal1m,
          geom=c("point","smooth"), method="lm") +
     facet_wrap(~Image,ncol=2)

line_data <- ggplot_build(p)$data[[2]]
line_data <- subset(line_data, PANEL == 1)
p + geom_line(data = line_data, aes(x = x, y = y, color = colour))

Another way to have gone about this would have been to fit linear models to each subset of data first, extracted their intercepts and slopes, and then used geom_abline(). For the reference line, I just plugged in the values of intercept and slope.

lmcoef <- ddply(vthcal1MIDAScal1m, "Image",
                   function(d) coef(lm(DN ~ temperature, data = d)))
names(lmcoef) <- c("Image", "b0", "b1")

ggplot(data=vthcal1MIDAScal1m, aes(x = temperature, y = DN)) +
    geom_point(aes(color = Image)) +
    geom_abline(data = lmcoef, aes(intercept = b0, slope = b1, color = Image)) +
    geom_abline(intercept = 29468.87, slope = 124.6561, color = "red") +
    facet_wrap(~ Image, ncol = 2)

I used ggplot() in this case because you want color to be mapped to points and the first call to geom_abline(), but not the second.

HTH,
Dennis


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

Agustin Lobo

unread,
Sep 19, 2012, 7:12:31 AM9/19/12
to Dennis Murphy, ggp...@googlegroups.com
Thanks for your detailed answer, it did help a lot.
The first solution looks initially simpler and more similar to what I
was doing, but I find using
ggplot_build(p)$data[[2]] very obscure. The second one is more clear
and actually calculating the
coefficients is something I had to do anyway.

Regards,
Agus
Reply all
Reply to author
Forward
0 new messages