Skip to content

Commit

Permalink
Merge pull request #203 from Doubt-0KB/master
Browse files Browse the repository at this point in the history
fixed `byrow=FALSE` reorder not only plots but also labels
  • Loading branch information
clauswilke authored Jan 12, 2025
2 parents e1334a2 + affdb46 commit 34819eb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
7 changes: 5 additions & 2 deletions R/plot_grid.R
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,11 @@ plot_grid <- function(..., plotlist = NULL, align = c("none", "h", "v", "hv"),
if (is.null(cols)) cols <- ceiling(num_plots/rows)
if (is.null(rows)) rows <- ceiling(num_plots/cols)

# if the user wants to layout the plots by column, we use the calculated rows to reorder plots
if (!isTRUE(byrow)) plots <- plots[c(t(matrix(c(1:num_plots, rep(NA, (rows * cols) - num_plots)), nrow = rows, byrow = FALSE)))]
# if the user wants to layout the plots by column, we use the calculated rows to reorder plots and labels
if (!isTRUE(byrow)){
plots <- plots[c(t(matrix(c(1:num_plots, rep(NA, (rows * cols) - num_plots)), nrow = rows, byrow = FALSE)))]
labels <- labels[c(t(matrix(c(1:num_plots, rep(NA, (rows * cols) - num_plots)), nrow = rows, byrow = FALSE)))]
}

# Align the plots (if specified)
grobs <- align_plots(plotlist = plots, align = align, axis = axis, greedy = greedy)
Expand Down
14 changes: 14 additions & 0 deletions tests/testthat/test_plot_grid.R
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,17 @@ test_that("alignment", {
plot_grid(p1, p2, ncol = 1, align = 'v', axis = "rl") + theme_map()
)
})



test_that("labels reorder by byrow", {
# byrow=TRUE
p_list <- lapply(1:3, \(x) ggplot())
g <- plot_grid(plotlist = p_list, ncol = 2, labels = 1:3, byrow = TRUE)
expect_equal(layer_data(g, 4)$label, 2)

# byrow=FALSE
p_list <- lapply(1:3, \(x) ggplot())
g <- plot_grid(plotlist = p_list, ncol = 2, labels = 1:3, byrow = FALSE)
expect_equal(layer_data(g, 4)$label, 3)
})

0 comments on commit 34819eb

Please sign in to comment.