I would like to use the same ggplot code to produce 8 different figures conditional upon figures in my dataframe. Usually I would use facet_grid, but in this case, I would like to end up with a pdf of each individual figure. For example, I would like one pdf for each row here:
df <- 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)
Basic ggplot:
library(ggplot2)
ggplot()+
geom_point(aes(x=xvalue, y=yvalue), data=df)
but instead of facet_grid
to get the location x planting x crop combos, I want one separate pdf of each.
First I made your MWE into a data.table
because it's 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 pasted together your planting
and corn
information to create a separate column:
df[ , plantingCrop := paste(df$planting, df$crop, sep = "-") ]
I created an character vector that has all combinations of planting
and crop
. You'll see why in a second:
plantingCrop1 <- unique(df$plantingCrop)
I use gridExtra
to create all of the plots in separate .pdf
pages. I basically created a loop that plots as many graphs as there are characters in the plantingCrop1
object I made above. In each loop, dat
is the subsetted group that you want to plot, by the unique plantingCrop
group from when we pasted the planting
and crop
columns together. It 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 right way to name the files using the plantingCrop
name as a subtitle. That's in the ggtitle
call.
I'd encourage you to change geom_boxplot(aes(color = location))
to geom_boxplot(aes(fill = location)
when you have more data as it shows up on a graph better, but I left it that way for now so you can see the different groups.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With