通过应用函数生成多个 ggplot 箱线图
Produce multiple ggplot boxplots through apply functions
我想知道是否可以使用应用函数生成一组与此嵌套循环组合生成的箱线图相似的箱线图。
它可能不是 possible/necessary 但我认为它应该是可能的,我只是不知道该怎么做。
我需要能够绘制此图以查看 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)
}
}
将 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)
我想知道是否可以使用应用函数生成一组与此嵌套循环组合生成的箱线图相似的箱线图。
它可能不是 possible/necessary 但我认为它应该是可能的,我只是不知道该怎么做。
我需要能够绘制此图以查看 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)
}
}
将 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)