R, ggplot, loop, for multiple panels

时间:2016-07-11 21:13:02

标签: r loops ggplot2 panels

Hey I am trying to do ggplot looping through 4 different cases, I have a data with 5 variables, I would like to plot out all points, regression lines, and add y=ax+b, and r^2 in the plots. All are plotted in a 4 panels plots. I use print(do.call(grid.arrange,plot) in the end, it will generate 4 panels in same plot

enter image description here

If I comment out this line, it generates:

enter image description here

As you can see, the scatter plots are different. I wonder why this happens. Also, the y=ax+b and r^2 look ugly, how to clean it up?

Thank you for your help

lm_eqn1 <- function(df,x,y){
  m <- lm(y ~ x, 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)))
  eq<-  substitute(italic(y) == b %.% italic(x)+ a,list(a = format(coef(m)[1], digits = 2),b = format(coef(m)[2], digits = 2)))
  as.character(as.expression(eq));
}
lm_eqn2 <- function(df,x,y){
  m <- lm(y ~ x, df);
  eq2<- substitute(italic(r)^2~"="~r2,
                   list(r2 = format(summary(m)$r.squared, digits = 3)))
  as.character(as.expression(eq2));
}

plot = list()
df <-    data.frame(as.vector(data[[1]]),as.vector(data[[2]]),as.vector(data[[3]]),as.vector(data[[4]]),as.vector(data[[5]]))
colnames(df) <- case
p = 1
for (k in 1:1){
  for (j in 2:5){
#    for (p in 1:4){
    x_lab <- paste(case[k]," [ug/m3]",sep=" ")
    y_lab <- paste(case[j]," [ug/m3]",sep=" ")
    x=df[,case[k]]
    y=df[,case[j]]
    print(case[k])
    print(case[j])
    plot[[p]] = ggplot(df,aes(x=x,y=y))+
                geom_point(size=2,alpha = 0.3,color="red")+
                theme_bw(base_size=12, base_family = "Helvetica")+
                xlab(x_lab)+
                ylab(y_lab)+
                theme(aspect.ratio=1)+
                ggtitle(case[j]) +
                geom_smooth(method='lm',se = FALSE, color="black",formula = y ~ x)+
                geom_text(x=-0.0005,y=0.05,label=lm_eqn1(df,x,y),parse = TRUE)+
                geom_text(x=-0.0005,y=0.04,label=lm_eqn2(df,x,y),parse = TRUE)
#    }
     print(plot[[p]])
     p = p + 1
}
}
#print(do.call(grid.arrange,plot))

1 个答案:

答案 0 :(得分:0)

黄。您的脚本对我很有帮助。对于您的问题,如果在ggplot()的第一行中使用'aes_string()'而不是'aes()',它将起作用。

ggplot(df, aes_string(x=x, y=y))