Skip to content
Learn Netverks
3

patchwork collects fill guides but not size guides when using wrap_plots()

asked 16 hours ago by @qa-hsgrmysdegpo6f4ljhyv 0 rep · 43 views

r patchwork

I have a function that is creating a bunch of plots and saving them in a list. When using patchwork::wrap_plots(), guides = "collect"collects the fill guide but not the size guide.

Expected output is a plot with one shared fill colorbar and one shared size legend at the bottom.

library(ggplot2)
library(patchwork)

set.seed(1)
df1 <- data.frame(x = rnorm(30), y = rnorm(30),
                  fill_var = runif(30), size_var = runif(30, 0.5, 1))
df2 <- data.frame(x = rnorm(30), y = rnorm(30),
                  fill_var = runif(30), size_var = runif(30, 0.5, 1))

make_panel <- function(df) {
  ggplot(df, aes(x, y)) +
    geom_point(aes(fill = fill_var, size = size_var), shape = 21) +
    scale_fill_viridis_b(breaks = c(0.25, 0.5, 0.75), limits = c(0, 1),
                         name = "Fill") +
    scale_size(range = c(2, 6), breaks = c(0.6, 0.75, 0.9),
               guide = guide_legend(title = "Size"))
}

wrap_plots(make_panel(df1), make_panel(df2), guides = "collect") &
  theme(legend.position = "bottom")

Comments on this question (0)

Use comments to ask for clarification — answers go in the answer box below.

Log in to comment on this question.

1

Because the size_var range differs in each df:

range(df1$size_var)
# [1] 0.5319042 0.9515408
range(df2$size_var)
# [1] 0.5319012 0.9947499

ggplot2 is defaulting to different size limits for each plot. To correct your issue, define the limits parameter in scale_size():

library(ggplot2)
library(patchwork)

make_panel <- \(df) {
  ggplot(df, aes(x, y)) +
    geom_point(
      aes(fill = fill_var, size = size_var),
      shape = 21
      ) +
    scale_fill_viridis_b(
      breaks = c(0.25, 0.5, 0.75),
      limits = c(0, 1),
      name = "Fill"
      ) +
    scale_size(
      range = c(2, 6),
      breaks = c(0.6, 0.75, 0.9),
      limits = c(0, 1),
      guide = guide_legend(title = "Size")
      )
}

wrap_plots(
  make_panel(df1),
  make_panel(df2),
  guides = "collect"
  ) &
  theme(legend.position = "bottom")

Note that the limits issue does not occur with scale_fill_viridis_b() and your sample data because you are forcing the scales to be discrete (binned).

Alex Hayes · 0 rep · 16 hours ago

Your answer