James
James

Reputation: 561

Getting Variable Names for X-Axis when Looping in ggplot?

I'm wondering if there is any way to insert the actual corresponding variable on the x-axis for each graph. In my actual dataset, I have 15 predictors. As it is not, for every graph, on axis, I just crime crime[,i].

Thanks!

Here is a minimal reproducible example:

y<- c(1,5,6,2,5,10) # response 
x1<- c(2,12,8,1,16,17) # predictor 
x2<- c(2,14,5,1,17,17)

crime <- data.frame(x1,x2,y)

for (i in 1:ncol(crime)){ 
  print(ggplot(crime, aes(x = crime[, i], y = y))+
    geom_point()) 
  Sys.sleep(2) 
} 

Upvotes: 1

Views: 927

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

You can iterate over column names in for loop and use them with .data in aes.

library(ggplot2)

for (col in names(crime)){ 
  print(ggplot(crime, aes(x = .data[[col]], y = y)) +  geom_point()) 
  Sys.sleep(2) 
} 

Upvotes: 1

akrun
akrun

Reputation: 887118

An option is to get the names based on the index, then convert to symbol and evaluate (!!)

for (i in 1:2){ # the first two columns are the 'x' columns
   print(ggplot(crime, aes(x = !! rlang::sym(names(crime)[i]), y = y))+
     geom_point()) 
     Sys.sleep(2) 
   }

Or another option is to keep the OP's code as such while adding a layer with xlab

for (i in 1:2){ # the first two columns are the 'x' columns
   print(ggplot(crime, aes(x = crime[,i], y = y))+
          geom_point() +
          xlab(names(crime)[i])) 
    Sys.sleep(2) 
      }

Upvotes: 2

Related Questions