I want to join three graphs with the patchwork package in R. I have also given an example that I prepared with Excel. I tried this code, but it didn't work.
library(patchwork)
patch_design <- c(area(1, 1, 1, 1),
area(1, 1, 1, 2),
area(1, 3, 1, 3))
graph1 + graph2 + graph3 + plot_layout(design= patch_design)
I am able to make a graph but i could not able to keep the graph-a to its original size.
Note that with {pathcwork}
layouts, you generally deal with relative measures and ratios, not absolute sizes. And grid definition with area()
goes like:
area(top, left, bottom, right)
, absolute values starting from top-left corner, values themselves define the layout grid size (i.e. if you only use 1
for all your top
and bottom
values, you'll end up having a single-row grid)
In many cases, it's more straightforward to describe the layout as a string, i.e. for the one in your image, it might take a form of
11111
22233
or
111111
222233
You can use almost any symbols you like, #
is a placeholder for empty grid cell, just be aware of the sorting order or your plots might not end up where you expected.
Let's start with the layout in question:
library(ggplot2)
library(patchwork)
## prepare example plots
ggplaceholder <- function(text, color){
ggplot() +
geom_tile(aes(x = 0, y = 0, width = 1, height = 1), fill = color, alpha = .5) +
geom_text(aes(x = 0, y = 0, label = text), size = 10) +
theme_minimal() +
theme(panel.background = element_rect(fill = "transparent"))
}
graph1 <- ggplaceholder("graph 1", "red")
graph2 <- ggplaceholder("graph 2", "green")
graph3 <- ggplaceholder("graph 3", "blue")
# current patch design,
# 1x3 gird (single row x 3 columns),
# grahp2 covers graph1:
patch_design <- c(area(1, 1, 1, 1), # 1 cell for g1, from top-left to top-left
area(1, 1, 1, 2), # 2 cells for g2, from top-left to top-middle
area(1, 3, 1, 3)) # 2 cell for g3, from top-right to top-right
graph1 + graph2 + graph3 + plot_layout(design = patch_design)
Changing it to 2 row layout:
# 2x5 grid
patch_design <- c(area(1, 1, 1, 5), # 5/5 of first row for g1
area(2, 1, 2, 3), # 3/5 of 2nd row for g2
area(2, 4, 2, 5)) # 2/5 of 2nd row for g3
graph1 + graph2 + graph3 + plot_layout(design = patch_design)
And the same with string definition:
# instead of area(), you can define a layout grid with a string,
# might be easier to follow and debug;
# identical to previous 2x5 grid:
patch_design_txt <- c("11111
22233")
graph1 + graph2 + graph3 + plot_layout(design = patch_design_txt)
Created on 2023-09-03 with reprex v2.0.2