0

I am trying to use a for loop to plot several columns of a datasets in separated boxplots. I was trying the code below but it returns empty boxplots

    #Select columns 
    num_vars_example = c('mpg', 'cyl', 'disp')
    
   for (i in num_vars_example) {
   print(
    ggplot(data = mtcars, aes(x = factor(0), i)) +
    geom_violin() +
    geom_boxplot(width=0.3, color="blue", alpha=0.2) + 
    theme(axis.title.x=element_blank(), 
    axis.text.x = element_blank(), 
    axis.ticks.x = element_blank())
  ) 
}

I realized that maybe the problem is that the i variable returns the name of the variables with quotes. So I changed the code for the example below but it returns an error

for (i in num_vars_example) {
   print(
    ggplot(data = mtcars, aes(x = factor(0), noquote(i))) +
    geom_violin() +
    geom_boxplot(width=0.3, color="blue", alpha=0.2) + 
    theme(axis.title.x=element_blank(), 
    axis.text.x = element_blank(), 
    axis.ticks.x = element_blank())
  ) 
}

Error: Discrete value supplied to continuous scale

How can I correct the code in order to plot several separated boxplots, one for each column?

If I run it outside the for loop it works

ggplot(data = mtcars, aes(x = factor(0), mpg)) + #Ploting mpg 
geom_violin() +
geom_boxplot(width=0.3, color="blue", alpha=0.2) + 
theme(axis.title.x=element_blank(), 
axis.text.x = element_blank(), 
axis.ticks.x = element_blank())
      
Rods2292
  • 665
  • 2
  • 10
  • 28
  • 1
    Please provide a reproducible example - in particular we need the structure of your `train` set. Have you got the code working for a single example, and it's just the loop that's causing an issue? – Paul Stafford Allen Feb 07 '23 at 16:41
  • I edited it and now it is reproducible. Yes, it is just the loop that is causing the issue – Rods2292 Feb 07 '23 at 16:50
  • 2
    As of ggplot version 3.0, the preferred way to do this is `aes(x = factor(0), y =.data[[i]])`. See the linked FAQ, particularly Tung's answer, for more details on this method. – Gregor Thomas Feb 07 '23 at 16:50

0 Answers0