0

I want to create multiple boxplots using for loop but having problems achieving the desired output.

Here as an example of what I have done:

library(ggplot2)
library(magrittr)
for(i in colnames(iris[1:4])) {
  print(iris %>% ggplot(aes(x = Species, y = i)) + geom_boxplot())
}

It is performing a loop but the output is just flat boxplots. Am I incorrect in assuming that where I put y = i, that the i value takes on the name of the column name through the iteration?

0

1 Answer 1

1

Basically you are telling ggplot to set y to the string "Sepal.Length" (in the first iterattion), and ggplot does not translate that to the column Sepal.Length.

Thus, you need to tell ggplot explicitly that you want the column and there are a couple of ways to do that.

Two examples below. The first is using the .data pronoun, which can be used in several places throughout the tidyverse to refer to the data.

The second option uses the quotation principles of the tidyverse.

library(ggplot2)
library(magrittr)
for(i in colnames(iris[1:4])) {
  dev.new()
  print(iris %>% ggplot(aes(x = Species, y = .data[[i]])) + geom_boxplot())
  ## or
  # print(iris %>% ggplot(aes(x = Species, y = !!sym(i))) + geom_boxplot()) 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.