for-loop to create ggplots

I trying to make boxplots with ggplot2.

The code I have to make the boxplots with the format that I want is as follows:

p <- ggplot(mg_data, aes(x=Treatment, y=CD68, color=Treatment)) + 
  geom_boxplot(mg_data, mapping=aes(x=Treatment, y=CD68))
p+ theme_classic() + geom_jitter(shape=16, position=position_jitter(0.2))

I can was able to use the following code to make looped boxplots:

variables <- mg_data %>%
  select(10:17)

for(i in variables) {                              
  print(ggplot(mg_data, aes(x = Treatment, y = i, color=Treatment)) +
          geom_boxplot())
}

With this code I get the boxplots however, they do not have the name label of what variable is being select for the y-axis, unlike the original code when not using the for loop. I also do not know how to add the formating code to the loop:

p + theme_classic() + geom_jitter(shape=16, position=position_jitter(0.2))

>Solution :

Here is a way. I have tested with built-in data set iris, just change the data name and selected columns and it will work.

suppressPackageStartupMessages({
  library(dplyr)
  library(ggplot2)
})

variables <- iris %>%
  select(1:4) %>%
  names()

for(i in variables) {
  g <- ggplot(iris, aes(x = Species, y = get(i), color=Species)) +
          geom_boxplot() +
    ylab(i)
  print(g)
}

Leave a Reply