patchwork icon indicating copy to clipboard operation
patchwork copied to clipboard

Problem while collecting axis titles and guides together

Open Soham6298 opened this issue 2 years ago • 1 comments

Hello,

I have encountered a problem with patchwork while collecting axis titles and guides together. I think this is the case when individual ggplots have multiple facets. What happens is that I can either collect the axis titles or the guides but not both. This could also happen when legend position is set to bottom. This code snippet should showcase the problem.

library(ggplot2)
library(patchwork)
#testdata
test1 = c(1, 2 ,3, 4)
test2 = c(4, 5, 6, 7) 
type1 = c('A', 'A', 'B', 'B')
type2 = c('C', 'C', 'D', 'D')
df <- data.frame(test1, test2, type1, type2)
df$facet1 <- c('1', '1', '2', '2')
df$facet2 <- c('3', '3', '4', '4')
#plot1
p1 <- ggplot(df, aes(x = test1, y = test2, colour = type1)) +
  theme_bw() +
  geom_point() +
  facet_wrap(~facet1) +
  labs(x = 'numbers', y = 'also numbers', guide = 'letters') +
  scale_colour_manual(values = c('red', 'green', 'blue'))
#plot2
p2 <- ggplot(df, aes(x = test1, y = test2, colour = type2)) +
  theme_bw() +
  geom_point() +
  facet_wrap(~facet2) +
  labs(x = 'numbers', y = 'also numbers', guide = 'letters') +
  scale_colour_manual(values = c('yellow', 'pink', 'orange'))
#combine
p <- (p1 + p2 + plot_layout(axis_titles = 'collect', guides = 'collect') &
        theme(legend.position = 'bottom'))
p

Resulting image: image

Soham6298 avatar Mar 28 '24 19:03 Soham6298

I encountered this as well. Collection works correctly when done for guides or axes, but not both. Here's a clearer reprex:

library(ggplot2)
library(patchwork)

plot_1 <- ggplot(mpg, aes(displ, hwy, colour = drv)) +
  geom_point() +
  facet_wrap(vars(drv))

plot_2 <- ggplot(mpg, aes(displ, cyl, colour = drv)) +
  geom_point() +
  facet_wrap(vars(drv))

# Guides are collected correctly:
plot_1 + plot_2 + plot_layout(ncol = 1, guides = "collect")

# Axes are collected correctly:
plot_1 + plot_2 + plot_layout(ncol = 1, axes = "collect")

# Bugged, only guides are collected:
plot_1 + plot_2 + plot_layout(ncol = 1, guides = "collect", axes = "collect")

Created on 2024-04-10 with reprex v2.0.2

mccarthy-m-g avatar Apr 10 '24 22:04 mccarthy-m-g