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))
CodePudding user response:
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)
}
Edit
Answering to a comment by user TarJae, reproduced here because answers are less deleted than comments:
Could you please expand with saving all four files. Many thanks.
The code above can be made to save the plots with a ggsave
instruction at the loop end. The filename is the variable name and the plot is the default, the return value of last_plot()
.
for(i in variables) {
g <- ggplot(iris, aes(x = Species, y = get(i), color=Species))
geom_boxplot()
ylab(i)
print(g)
ggsave(paste0(i, ".png"), device = "png")
}
CodePudding user response:
Try this:
variables <- mg_data %>%
colnames() %>%
`[`(10:17)
for (i in variables) {
print(ggplot(mg_data, aes(
x = Treatment, y = {{i}}, color = Treatment
))
geom_boxplot())
}
CodePudding user response:
Another option is to use lapply
. It's approximately the same as using a loop, but it hides the actual looping part and can make your code look a little cleaner.
variables = iris %>%
select(1:4) %>%
names()
lapply(variables, function(x) {
ggplot(iris, aes(x = Species, y = get(x), color=Species))
geom_boxplot() ylab(x)
})