0
library(grid)
library(gridExtra)

plot_freq <- function(arrs){

  g <- list()

  for(i in c(1:length(arrs))){
    y_val <- get(arrs[i])
    g[[i]] <- qplot(y = y_val, x = c(1,2,3,4,5))
    print(g[[i]])
  }
  grid.arrange(grobs = g, ncol= 3)
}

a <- c(4,4,4,4,4)
b <- c(5,5,5,5,5)
c <- c(6,6,6,6,6)
plot_freq(c("a", "b", "c"))

Above code results in three same plots (same like last plot i.e. array c) in grid.arrange but if we plot them separately, they work fine. Any way I should change my code to get it working?

Arch Desai
  • 191
  • 1
  • 8

1 Answers1

1

It looks like the data frame needs to be generated when storing the plots in a loop. The following works as expected. Please see this link for a more detailed discussion: Storing plot objects in a list

library(grid)
library(gridExtra)
library(ggplot2)

plot_freq <- function(arrs){

  g <- list()

  for(i in c(1:length(arrs))){
    y_val <- get(arrs[i])
    g[[i]] <- qplot(data = data.frame(y = y_val, x = c(1,2,3,4,5)), x , y) 
    #g[[i]] <- qplot(y = y_val, x = c(1,2,3,4,5))
  }
  grid.arrange(grobs = g, ncol= 3)
}

a <- c(4,4,4,4,4)
b <- c(5,5,5,5,5)
c <- c(6,6,6,6,6)
plot_freq(c("a", "b", "c"))

generating this plot (please note Y-axis is different) in each sub-plot.

enter image description here

Seshadri
  • 669
  • 3
  • 11