6

I have a dataframe filter, which is a subset of dataframe df2, which was made with dyplr's mutate() function.

I want to loop through some columns and make scatterplots with them.

My loop:

colNames <- names(filter)[9:47]
for(i in colNames){
  ggplot(filter, aes(x=i, y=CrimesPer10k)) +
    geom_point(color="#B20000", size=4, alpha=0.5) +
    geom_hline(yintercept=0, size=0.06, color="black") + 
    geom_smooth(method=lm, alpha=0.25, color="black", fill="black")
}

Yet I get no output, nor any errors.

What am I doing wrong?

RBPB
  • 73
  • 1
  • 1
  • 4

2 Answers2

20

You need to explicitly print() the object returned by ggplot() in a for loop because auto-print()ing is turned off there (and a few other places).

You also need to use aes_string() in place of aes() because you aren't using i as the actual variable in filter but as a character string containing the variable (in turn) in filter to be plotted.

Here is an example implementing both of these:

Y <- rnorm(100)
df <- data.frame(A = rnorm(100), B = runif(100), C = rlnorm(100),
                 Y = Y)
colNames <- names(df)[1:3]
for(i in colNames){
  plt <- ggplot(df, aes_string(x=i, y = Y)) +
    geom_point(color="#B20000", size=4, alpha=0.5) +
    geom_hline(yintercept=0, size=0.06, color="black") + 
    geom_smooth(method=lm, alpha=0.25, color="black", fill="black")
  print(plt)
  Sys.sleep(2)
}
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
2

aes_string() was deprecated in ggplot2 > 3.0.0 but .data[[]] can be used.

colNames <- names(filter)[9:47]
for(i in colNames){
  plt <- ggplot(filter, aes(x=.data[[i]], y=CrimesPer10k)) +
    geom_point(color="#B20000", size=4, alpha=0.5) +
    geom_hline(yintercept=0, size=0.06, color="black") + 
    geom_smooth(method=lm, alpha=0.25, color="black", fill="black")
print(plt)
}
Ajay
  • 184
  • 1
  • 7