【问题标题】:Produce multiple ggplot boxplots through apply functions通过apply函数产生多个ggplot箱线图
【发布时间】:2015-02-13 08:17:00
【问题描述】:

我想知道是否可以使用 apply 函数生成一组类似于嵌套循环组合生成的箱线图。

这可能是不可能/必要的,但我认为它应该是可能的,我只是不知道该怎么做。

我需要能够对此进行绘制,以查看 100 个因素如何比较一个变量 (mtcars$mpg)

head(mtcars)

for (i in 8:11) {
    for (j in 8:11) {

        if (i != j) {

            title = paste(names(mtcars)[i], names(mtcars)[j], 
                sep = "/")

            p <- ggplot(mtcars, aes(interaction(mtcars[,i], mtcars[, j]), mpg, fill = factor(mtcars[,i]))) + geom_boxplot(alpha = I(0.7))
            p <- p + ggtitle(title) + scale_fill_hue()


        } else {

            title = paste(names(mtcars)[i])

            p <- ggplot(mtcars, aes(factor(mtcars[,i]), mpg, fill = factor(mtcars[, i]))) + geom_boxplot(alpha = I(0.7))
            p <- p + ggtitle(title) + scale_fill_hue()


        }

        print(p)
    }
} 

【问题讨论】:

    标签: r ggplot2 apply


    【解决方案1】:

    将 if 块放入函数中:

    plotGG <- function(i,j) 
      {
      if (i != j) { ... } else{ ... }
     }
    

    然后调用它:

    mapply(plotGG,8:11,8:11)
    

    而且它有效。

    由于ggplot 的范围问题,您的代码将无法工作。但您可以在此处查看解决方案: Local Variables Within aes

    编辑: 您可以根据需要完成包装:

    multiPlotGG <- function(l1,l2) {
     mapply(plotGG,rep(l1,each = length(l2)),rep(l2,length(l1)))
    }
    multiPlotGG(8:11,8:11)
    

    【讨论】:

    • mapply 在你的答案中只会产生四个与 i=j 的组合
    • 谢谢@MaratTalipov。先前的解决方案是指向正确的方向。用包装器更新。
    • 干杯,伙计们 :) 应用函数对我来说真的不直观!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2021-08-04
    • 2021-11-10
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多