How to add regression line to faceted plots with coord_trans() axes?

23 views
Skip to first unread message

Thomas

unread,
Sep 9, 2014, 5:03:20 PM9/9/14
to ggp...@googlegroups.com
I would like to add regression lines to faceted plots that have a transformed axis. I am having trouble getting geom_abline() and coord_trans() to work together. I can imagine that this might not work, but I do not fully understand why it doesn't work. (example code adapted from stackoverflow). I am assuming the explanation for why this doesn't work and the solution for making it work are obvious, but I am not seeing them...

require(ggplot2)
require(plyr)
###generate fake data
df <- data.frame(x = c(1:98)/100)
df$y <- 2 + 3 * df$x + rnorm(98, sd = 40)

#############################################################
##create a function to extract linear model parameters from transformed data
#############################################################
lm_eqn = function(df){
  m = lm(y ~ asin(sqrtx, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
                   list(a = format(coef(m)[1], digits = 2), 
                        b = format(coef(m)[2], digits = 2), 
                        r2 = format(summary(m)$r.squared, digits = 3)))
 c(a = format(coef(summary(m))[1,1], digits = 2), 
   b = format(coef(summary(m))[2,1], digits = 2),
  eq=as.character(as.expression(eq)))                 
}

df$group <- c(rep(1:2,49))
eq <- ddply(df,.(group),lm_eqn)
eq$a<-as.numeric(eq$a)
eq$b<-as.numeric(eq$b)

##################################################
#Untransformed axes displaying regression line from transformed data
##################################################

x11()
p<-ggplot(data = df, aes(x = x, y = y)) +
  #coord_trans(xtrans="asn")+
  geom_abline(aes(intercept=a, slope=b), data=eq)+
  geom_point()
p1 = p + geom_text(data=eq,aes(x = 0.25, y = 0,label=eq), parse = TRUE, inherit.aes=FALSE) + facet_grid(group~.)
p1 
#################################################
##Transformed axes but regression line won't display
###############################################
x11()
p<-ggplot(data = df, aes(x = x, y = y)) +
  coord_trans(xtrans="asn")+
  geom_abline(aes(intercept=a, slope=b), data=eq)+
  geom_point()
p1 = p + geom_text(data=eq,aes(x = 0.25, y = 0,label=eq), parse = TRUE, inherit.aes=FALSE) + facet_grid(group~.)
p1 

Reply all
Reply to author
Forward
0 new messages