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.
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
)
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:
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
. But you can view the solution here: Local Variables Within 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.