0
votes

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"))
ggdraw(leg123)

result

What I would like to have would look like this:

What I want is:

1

1 Answers

0
votes

The output of ggplot2 and any other R application that uses the graphics device is related directly to the resolution and size of your graphics window. Basically, the text and some other drawn layers scale differently from one another, which means that if you change the size of your window, the output changes. If I take your code, you can see the effect by sending different width= and height= arguments to ggsave():

# kind of the default output for me
ggsave('a0.png', width=8, height=5)

enter image description here

# this gets you something like what you wanted
ggsave('a.png', width=3, height=2)

enter image description here

Now, if you put that along with a plot... use the same general idea and you should be able to arrive at something that works.