0

I have really strange problem... I'm trying to create plots in a loop and put them to the list and after that drew them all on one page. when I do it:

for (i in 1:ncol(df)){ 
   plot[[i]] <- ggplot(df, aes(x = df[,i], y=(..count..)/sum(..count..))) + 
     geom_bar(fill="#003366") + 
     labs(title = dfcolnames[i], x = "Variable Values", y = "Frequency") 
}
return(multiplot(plotlist=plot, cols = 2))

I get 3 this same plots, but when I do it without for loop:

plot[[1]] <- ggplot(df, aes(x = df[,1], y=(..count..)/sum(..count..))) + geom_bar(fill="#003366") + labs(title = dfcolnames[1], x = "Variable Values", y = "Frequency")
plot[[2]] <- ggplot(df, aes(x = df[,2], y=(..count..)/sum(..count..))) + geom_bar(fill="#003366") + labs(title = dfcolnames[2], x = "Variable Values", y = "Frequency") 
plot[[3]] <- ggplot(df, aes(x = df[,3], y=(..count..)/sum(..count..))) + geom_bar(fill="#003366") + labs(title = dfcolnames[3], x = "Variable Values", y = "Frequency") 
return(multiplot(plotlist=plot, cols = 2))

I get correct plots (three different). I don't understand what is going on.... Any ideas?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
tomsu
  • 371
  • 2
  • 16
  • 3
    You should read `ggplot2` tutorial on how to plot wide/long data and fill bars by variable instead of creating three different plots. – pogibas Jan 02 '18 at 21:27
  • but what is wrong with loop that i created? – tomsu Jan 02 '18 at 21:38
  • 1
    Not sure - works fine for me when I replace `df` with `mtcars`. But you're really not using `ggplot` the way it's supposed to be used. – Gregor Thomas Jan 02 '18 at 21:43

1 Answers1

4

The problem is that aes() performs lazy evaluation. The values you pass to aes() are only resolved when you actually draw the plot. You really should only be passing symbol names to aes(). This is because after the loop ends, i will be fixed at it's last value from the loop and you'll just get the same plot three times.

You could instead use aes_string and loop over the column names

plot <- lapply(names(df), function(colname) {
  ggplot(df, aes_string(x = colname, y="(..count..)/sum(..count..)")) + 
           geom_bar(fill="#003366") + 
           labs(title = colname, x = "Variable Values", y = "Frequency") 
})

Tested with

set.seed(10)
df <- data.frame(a=rpois(100, 5), b=rpois(100, 7), c=rpois(100, 3))
MrFlick
  • 195,160
  • 17
  • 277
  • 295