Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading