Home > Mobile >  make ggplot looping through columns R
make ggplot looping through columns R

Time:10-27

I am trying to teach myself how to do ggplots by looping over a df in R. I am trying to use the advice given here: how-do-i-loop-through-column-names-and-make-a-ggplot-scatteplot-for-each-one

I have a df:

  Sample_ID <- c("P1014B", "P1014F", "P1036A")
  SCORE <- c(2677, 1021, 870)
  P_VALUE <- c(0.101, 1.000, 1.000)
  df<- data.frame(Sample_ID, SCORE, P_VALUE)
> df
  Sample_ID SCORE P_VALUE
1    P1014B  2677   0.101
2    P1014F  1021   1.000
3    P1036A   870   1.000

I try to loop and plot (I want to plot the 2nd and 3rd column as y and use 1st column as x axis):

 colNames <- names(df)[2:3]
  for(i in colNames){
    #  print(i)
    plt = ggplot(df, aes_string(x=df[1], y =i)) 
    print(plt)
    Sys.sleep(2)
  }

But I get:

Error in `FUN()`:
! Unknown input: data.frame
Run `rlang::last_error()` to see where the error occurred. 

Ideally I want to output the plots to a pdf and I have the code that works on each plot generated separately (at the moment I have 5 plots but have used the example above with 2 columns for ease of understanding):

  pdf(file=paste0(path,"my.pdf")) 

  print(ggarrange(b,nrow=1,ncol=1,
             ggarrange(a, c, ncol=1,nrow=2),
             ggarrange(d, e, ncol=1,nrow=2)))
         
   dev.off()

CodePudding user response:

You need to access the colname, not the content of the column:

 colNames <- names(df)[2:3]
  for(i in colNames){
    #  print(i)
    plt = ggplot(df, aes_string(x=colnames(df)[1], y =i)) 
    print(plt)
    Sys.sleep(2)
  }
  • Related