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())