First I made your MWE in data.table because it is faster
library(data.table) library(ggplot2) library(gridExtra) df <- data.table(read.table(text = " xvalue yvalue location planting crop 1 5 A early corn 2 3 A late corn 6 2 A early soy 7 4 A late soy 4 7 S early corn 2 6 S late corn 3 2 S early soy 5 1 S late soy ", sep = "", header = TRUE))
I inserted your planting and corn data to create a separate column:
df[ , plantingCrop := paste(df$planting, df$crop, sep = "-") ]
I created a character vector that has all combinations of planting and crop . You will see why in a second:
plantingCrop1 <- unique(df$plantingCrop)
I use gridExtra to create all the charts on separate .pdf pages. I basically created a loop that displays as many plots as there are characters in the plantingCrop1 object, which I made above. In each loop, dat is the subgroup you want to build using the unique plantingCrop group when we inserted the planting and crop columns together. He repeats this until everything is done.
pdf("plantingCrop.pdf", onefile = TRUE) for(i in 1:length(plantingCrop1)){ dat <- subset(df, plantingCrop==plantingCrop1[i]) cropPlot <- ggplot(dat, aes(xvalue,yvalue)) + geom_boxplot(aes(color = location)) + theme_bw() + ggtitle(bquote(atop(.("Boxplot of Stuff"), atop(italic(.(plantingCrop1[i])), "")))) + labs(x = "xvalue", y = "yvalue") + theme(legend.position = "top", legend.title=element_blank()) grid.arrange(cropPlot) } dev.off()
I also included the correct way to name files using the name plantingCrop as subtitles. This is in the ggtitle call.
I would recommend that you change geom_boxplot(aes(color = location)) to geom_boxplot(aes(fill = location) when you have more data, because it displays better on the graph, but I left it so that you can see different groups .