Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through column names and make a ggplot scatteplot for each one

Tags:

r

ggplot2

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?

like image 373
RBPB Avatar asked Apr 03 '15 03:04

RBPB


1 Answers

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)
}
like image 69
Gavin Simpson Avatar answered Nov 15 '22 06:11

Gavin Simpson