Using lapply to make boxplots of a variable list

1.7k Views Asked by At

I want this type of boxplot for several y-variables in my dataset: normal boxplot for all irises with Species as x-value. Since I have multiple y variables to plot, I tried to use lapply like this:

varlist <- c('Sepal.Length', 'Sepal.Width')

plot <- function (varlist) {
  require(ggplot2)
  ggplot(data = iris, aes(x=Species, y=varlist))+
    geom_boxplot() 
}

lapply(varlist, FUN = plot)

I got this plot: with only one iris per plot

How can I get normal boxplots using a type of loop (because of several y-values), and where all irises grouped by the x-variable are included in the boxes?

2

There are 2 best solutions below

0
On BEST ANSWER

IIRC, aes() does not handle string inputs; you need aes_string(). I expect (but have not tested) that your function will work if you change you ggplot() call to ggplot(data = iris, mapping = aes_string(x = 'Species', y = varlist)).

0
On

With dplyr you could do:

library("ggplot2")
library("dplyr")


varlist <- c('Sepal.Length', 'Sepal.Width')

customPlot <- function(varName) {

iris %>% 
group_by_("Species") %>% 
select_("Species",varName) %>% 
ggplot(aes_string("Species",varName)) + geom_boxplot()

}
lapply(varlist,customPlot)

Plots:

enter image description here

enter image description here

Also note that plot is a base function for general plotting.It is not safe to overwrite base functions with user defined functions as it could lead to unexpected results later.