can not collect legend with plot_layout() from patchwork package in r

800 Views Asked by At

Just as the title. I have a plot.

p <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

When I use + to combine plots, I can collect legend.

p + p + plot_layout(guides = 'collect')

When I use | to combine plots, I can NOT collect legend.

p | p + plot_layout(guides = 'collect')

I do not why.

What is the difference between | and +, and When use |, when use +.

Any help will be highly appreciated.

1

There are 1 best solutions below

1
On

This is because of how the nesting level is calculated according to operator precedence.

p + p + plot_layout(guides = 'collect')

is interpreted as

((p + p) + plot_layout(guides = 'collect'))

Whereas

p | p + plot_layout(guides = 'collect')

is interpreted as

p | (p + plot_layout(guides = 'collect')

Whereas you want

(p | p) + plot_layout(guides = 'collect')

enter image description here