Home > database >  ggarrange disrupts legend key size and creates white space
ggarrange disrupts legend key size and creates white space

Time:12-26

One of my plot contains legend and the other does not. They are alright when plotted and exported separately. However, merging these two figures using "ggarrange" creates white spaces in the left and legend key size also goes haywire. Here is the code I concocted with "iris" dataset.

library(tidyverse)
library(ggpubr)
library(showtext)

showtext_auto()  ##It reduces font size to a customization friendly level

setwd("C:/Users/mdnah/Desktop")

A<- iris %>% 
  gather(key="cat", value = "value", -Species) %>% 
  group_by(Species, cat) %>% 
  summarise(mn= mean(value)) %>%
  filter(Species!="setosa") %>% 
  ggplot(aes("", mn, fill=cat)) 
  geom_bar(stat = "identity", position = "fill") 
  scale_fill_discrete(name=NULL, guide= guide_legend(label.position = "left")) 
  coord_polar(theta = "y", start = 0) 
  facet_wrap(~Species, nrow=1) 
  theme_void() 
  theme(text = element_text(family = "serif", size = 20, lineheight = 0.3),
        legend.box.margin = margin(-20,-10,0,0),
        legend.spacing.x = unit(0.2, "cm"),
        legend.key.size = unit(0.3, "cm"),
        legend.position="left")
print(A)
# ggsave("FigA.jpg", width = 4, height = 2)

B<- iris %>% 
  gather(key="cat", value = "value", -Species) %>% 
  group_by(Species, cat) %>% 
  summarise(mn= mean(value)) %>%
  filter(Species!="setosa") %>% 
  ggplot(aes(mn, reorder(cat, mn))) 
  geom_bar(stat = "identity", width = 0.7) 
  scale_x_continuous(expand = c(0,0)) 
  facet_wrap(~Species, nrow = 1) 
  theme_minimal() 
  theme(axis.text = element_text(colour = "black", lineheight = 0.3),
        text = element_text(family = "serif", size = 20),
        strip.text = element_blank(),
        panel.spacing = unit(1, "cm"),
        axis.title = element_blank())
print(B)
# ggsave("FigB.jpg", width = 4, height = 2.5)

ggarrange(A, B, nrow=2)
ggsave("FigAB.jpg", width = 4, height = 4.5) #widths are equal, so I just added up the heights.

Current image

enter image description here

Desired image:

enter image description here

list of things I tried

  1. Tried separating legend grob using get_legend() but couldn't place them in the desired area.

  2. Tried nested ggarrange (Top- legend of plot A plot A, Bottom- plot B).

  3. I discovered small font size does not distort legend keys in ggarrange, thought it was due to "lineheight" but it wasn't.

My guess is, it is something to do with font size or margin of any element.

CodePudding user response:

One option would to switch to patchwork and wrap your plots inside wrap_elements. Additionally I used the heights argument of plot_layout` to reduce the white space above and below the pie chart:

library(patchwork)

wrap_elements(A) / wrap_elements(B)   plot_layout(heights = c(1, 1.5))

ggsave("FigAB.jpg", width = 4, height = 4.5)

enter image description here

  • Related