Home > Software design >  Using cowplot in R to make a ggplot chart occupy two consecutive rows
Using cowplot in R to make a ggplot chart occupy two consecutive rows

Time:12-21

This is my code:

library(ggplot2)
library(cowplot)


df <- data.frame(
  x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4
)

p1 <- ggplot(df, aes(x, y1))   geom_point()
p2 <- ggplot(df, aes(x, y2))   geom_point()
p3 <- ggplot(df, aes(x, y3))   geom_point()
p4 <- ggplot(df, aes(x, y4))   geom_point()
p5 <- ggplot(df, aes(x, y3))   geom_point()
# simple grid
plot_grid(p1, p2, 
          p3, p4,
          p5, p4)

But I don't want to repeat p4 I want to "stretch" p4 to occupy col2 and rows 2 and 3.

Any help?

CodePudding user response:

You may find this easier using gridExtra::grid.arrange().

library(gridExtra)

grid.arrange(p1, p2, p3, p4, p5, 
             ncol = 2, 
             layout_matrix = cbind(c(1,3,5), c(2,4,4)))

Result:

enter image description here

CodePudding user response:

Is this what you are trying to achieve?

library(ggplot2)
library(cowplot)

df <- data.frame(
  x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4
)

p1 <- ggplot(df, aes(x, y1))   geom_point()
p2 <- ggplot(df, aes(x, y2))   geom_point()
p3 <- ggplot(df, aes(x, y3))   geom_point()
p4 <- ggplot(df, aes(x, y4))   geom_point()
p5 <- ggplot(df, aes(x, y3))   geom_point()
# simple grid
plot_grid(p1, p2, 
          p3, p5,
          p4, p4)

grid_top <- plot_grid(p1, p2, p3, nrow = 1)
grid_bottom <- plot_grid(p3, p4, nrow = 1, rel_widths = c(0.33, 0.66))
plot_grid(grid_top, grid_bottom, nrow = 2)

Created on 2021-12-21 by the reprex package (v2.0.1)

CodePudding user response:

This is fairly straight forward with the patchwork package.

library(ggplot2)
library(patchwork)


df <- data.frame(
  x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4
)
make_p <- function(y){
  ggplot(df, aes(x, !!sym(y)))   geom_point()
}

## custom layout grid
layout <- "
AB
CD
ED
"

ls_p <- lapply(paste0("y", c(1:4,3)), make_p)

wrap_plots(ls_p)   plot_layout(design = layout)

Created on 2021-12-21 by the reprex package (v2.0.1)

  • Related