9

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?

2 Answers 2

21

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)
}
Sign up to request clarification or add additional context in comments.

Comments

11
Answer recommended by R Language Collective

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.