Home > front end >  ggplot and ggarrange - how to prevent legend box from being cut off?
ggplot and ggarrange - how to prevent legend box from being cut off?

Time:01-23

For me this issue only happens on Mac. Unfortunately I am traveling and I only have my Macbook with me. Here is a minimal example. The problem doesn't appear in individual plots, but only when they are joined via ggarrange.

library(ggplot2)
library(ggpubr)

p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am)))  
  geom_point()  
  theme(legend.box.background = element_rect(color = "black", size = 1))

p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am)))  
  geom_point()  
  theme(legend.box.background = element_rect(color = "black", size = 1))

ggarrange(p1, p2, common.legend = T, legend = "right")

Now look at the graph:

enter image description here

As you can see, the right border of the legend box is cut off. How do I prevent it from doing so?

CodePudding user response:

If you want to stick with ggpubr here is a solution that is admittedly not great but works.

library(ggplot2)
library(ggpubr)

p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am)))  
  geom_point()  
  theme(legend.box.background = element_rect(color = "white", linewidth  = 1),
        legend.background = element_rect(color = "black", linewidth  = 1),
        legend.box.margin = margin(r = 20))

p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am)))  
  geom_point()  
  theme(legend.box.background = element_rect(color = "white", linewidth  = 1),
        legend.background = element_rect(color = "black", linewidth  = 1),
        legend.box.margin = margin(r = 20))

ggarrange(p1, p2, common.legend = T, legend = "right")

enter image description here

CodePudding user response:

One option would be to switch to patchwork to glue your plots together:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars, aes(x = mpg, y = disp, color = as.factor(am)))  
  geom_point()

p2 <- ggplot(mtcars, aes(x = hp, y = disp, color = as.factor(am)))  
  geom_point()

p1   p2  
  plot_layout(guides = "collect") &
  theme(legend.box.background = element_rect(color = "black", size = 1))

  • Related