问题
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?
回答1:
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))
.
回答2:
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:
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.
来源:https://stackoverflow.com/questions/41218249/using-lapply-to-make-boxplots-of-a-variable-list