Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ggplot and ggarrange – how to prevent legend box from being cut off?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading