How to deminish margins between legends in ggplot2
Entering edit mode
23 months ago
YiweiZhu ▴ 30

Hi, everyone!

Arranging multiple legends is a common issue when preparing plots in R. The theme() function in ggplot2 package allows to arrange multiple legends in either horizontal or vertical direction.

However, in some cases, some legends are long, and others are short. It is prefered to stack the short legends in a row or a column while leaving the long legend in another single row or column. The only two choices "horizontal" or "vertical" in the theme() function are unsatisfying.

Another way is to extract legends from plots by the get_legend() function in the cowplot package. However, the margins between the legends cannot be deminished after arranged by the plot_grid() function. How could I deminish the margins (grey area) between legends?

A reproducible examples showed below:

p1 <- ggplot(mtcars) +
  geom_bar(aes(x=as.factor(am), fill=as.factor(am))) +
  theme(legend.margin = margin(0,unit="pt"))
p2 <- ggplot(mtcars) +
  geom_bar(aes(x=as.factor(vs), fill=as.factor(vs))) +
  theme(legend.margin = margin(0,unit="pt"))
p3 <- ggplot(mtcars) +
  geom_bar(aes(x=as.factor(carb),fill=as.factor(carb))) +
  scale_fill_manual(breaks = c(1,2,3,4,5,6,7,8),values = c('#f7fcfd','#e5f5f9','#ccece6','#99d8c9','#66c2a4','#41ae76','#238b45','#005824'))+
  theme(legend.margin = margin(0,unit="pt"))
leg1 <- get_legend(p1+theme(legend.background = element_rect(fill="white")))
leg2 <- get_legend(p2+theme(legend.background = element_rect(fill="white")))
leg3 <- get_legend(p3+theme(legend.background = element_rect(fill = "white")))
leg12 <- plot_grid(leg1,leg2,nrow=2)+theme(plot.background = element_rect(fill="grey"))
leg123 <- plot_grid(leg3,leg12,nrow = 1)+theme(plot.background = element_rect(fill="grey"))


R ggplot2 cowplot • 1.7k views

Login before adding your answer.

Traffic: 1478 users visited in the last hour
Help About
Access RSS

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6