[英]Produce multiple ggplot boxplots through apply functions
I was wondering if it was possible to produce a set of boxplots similar to that produced by this nested loop combinations using an apply function. 我想知道是否有可能使用apply函数生成一组类似于这个嵌套循环组合产生的箱图。
It may not be possible/necessary but I thought it should be possible, I just cant wrap my head around how to do it. 这可能是不可能/必要的,但我认为应该是可能的,我只是无法绕过如何做到这一点。
I need to be able to plot this to see how 100s of factors compare in respect to one variable ( mtcars$mpg
) 我需要能够绘制这个以查看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)
}
}
Put the if block in a function: 将if块放在函数中:
plotGG <- function(i,j)
{
if (i != j) { ... } else{ ... }
}
Then call it: 然后叫它:
mapply(plotGG,8:11,8:11)
And it works. 它有效。
Your code will not work due to a scoping issue with ggplot
. 由于ggplot
的范围问题,您的代码将无法ggplot
。 But you can view the solution here: Local Variables Within aes 但是你可以在这里查看解决方案: aes中的局部变量
EDIT: You can finish wrap it as you want: 编辑:您可以根据需要完成包装:
multiPlotGG <- function(l1,l2) {
mapply(plotGG,rep(l1,each = length(l2)),rep(l2,length(l1)))
}
multiPlotGG(8:11,8:11)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.