Using lapply to make boxplots of a variable list

穿精又带淫゛_ 提交于 2020-06-28 04:44:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!