I have several Plots, all build out of facets of various numbers, but all with a fixed aspect ratio (See Picture). How can I combine all of them in one Plot, where the individual facets have the same size, while at the same time minimizing the unused space (here green).
I tried to do it with cowplot::plot_grid and fiddling with rel_hight, rel_width, and a filler Plot. Which kind of works, but is tedious and depends on the final image size (ggsave width). It feels like there must be a more robust and reliable way to achieve it?
#Combing the Plots
plot_grid(
plot_grid(p1,p2, nrow = 2, rel_widths = c(1,1), labels = c("A","C")) ,
plot_grid(p2,pN, nrow=2, rel_heights = c(1,0.45), labels=c("B","")),
plot_grid(p3,p4,pN, nrow = 3, rel_heights = c(1.6,1,0.6), labels=c("D","E","")),
nrow = 1, rel_widths = c(1,1.4,0.65), labels = c("","B",""))
ggsave("example.png", width = 8, height = 5.35, bg="green")
Below is a minimal example to generate the data.
library(cowplot)
#Generate Test Data
counter <- 0
for (YAxis in paste(letters[1:4], "Axis")) {
for (XAxis in paste(letters[1:4], "Axis")) {
for (rows in c("A","B","C")) {
for (col in c("A","B","C")) {
counter <- counter + 1
tmp <- data.frame(YAxis,XAxis,rows,col, value=rnorm(1))
if (counter == 1) { df <- tmp }
if (counter != 1) { df <- rbind(df, tmp) }
}
}
}
}
#Plot Function
myPlotFnc <- function(subDF){
p <- ggplot(subDF,aes(col,rows,fill= value))+
geom_tile()+
facet_grid(YAxis ~XAxis,switch="both")+
coord_fixed()+ theme(legend.position = "none")
return(p)
}
#filler plot
pN <- ggplot(data.frame(x=1,y=1), aes(x,y))+geom_blank()+ theme_void()
#generating Example Plots
p1 <- myPlotFnc(df[(df$YAxis == "a Axis" & df$XAxis== "a Axis") |
(df$YAxis == "b Axis" & df$XAxis== "b Axis") |
(df$YAxis == "a Axis" & df$XAxis== "b Axis") |
(df$YAxis == "b Axis" & df$XAxis== "a Axis"),] )
p2 <- myPlotFnc(df[(df$YAxis == "a Axis" & df$XAxis== "a Axis") |
(df$YAxis == "b Axis" & df$XAxis== "b Axis") |
(df$YAxis == "a Axis" & df$XAxis== "b Axis") |
(df$YAxis == "c Axis" & df$XAxis== "c Axis") |
(df$YAxis == "c Axis" & df$XAxis== "a Axis") |
(df$YAxis == "b Axis" & df$XAxis== "a Axis"),] )
p3 <- myPlotFnc(df[(df$YAxis == "a Axis" & df$XAxis== "c Axis") |
(df$YAxis == "b Axis" & df$XAxis== "c Axis"),] )
p4 <- myPlotFnc(df[(df$YAxis == "d Axis" & df$XAxis== "d Axis") ,] )
Edit: Adjusted rel. width sizes a bit more to get closer to the desired plot.