Search code examples
rlegendcowplot

How to remove awkward vertical gap between the two legends I created for Cowplot in R?


I tried to create two separate legends because I wanted to group my legends differently. However, there is this awkward gap between both legends; I want to close the awkward vertical gap between the two legends (as pictured). How can I go about doing so?

Thank you.

picture here

library(cowplot)

data2 <- tibble::tribble(
  ~Color,    ~Item, ~Count,       ~Year,
  "Blue",    "Bag",     50, "2009-2011",
  "Blue", "Wallet",     60, "2009-2011",
  "Green",  "Shoes",     80, "2009-2011",
  "Green",  "Shirt",     90, "2009-2011",
  "Yellow", "Flower",     20, "2009-2011",
  "Yellow",   "Bees",     30, "2009-2011",
  "Blue",    "Bag",     50, "2009-2012",
  "Blue", "Wallet",     60, "2009-2012",
  "Green",  "Shoes",     90, "2009-2012",
  "Green",  "Shirt",     20, "2009-2012",
  "Yellow", "Flower",     10, "2009-2012",
  "Yellow",   "Bees",      5, "2009-2012"
)

palette1 <- c("#4575B4","#74ADD1","#ABD9E9","#800026","#FC4E2A","#FEB24C")
palette2 <- c("#800026","#FC4E2A","#FEB24C")

data2$Count_final <- with(data2, Count * c(1, -1)[(Color == "Yellow") + 1])


full_plot <- ggplot(data=data2)+ 
    geom_bar(aes(x=Year,y=Count_final,fill=Item),stat="identity",position="identity") +
    scale_y_continuous(labels=abs)+
    scale_fill_manual(values=palette1)+
    theme_bw(base_size=18) +
    ylab("Count")+
    theme(legend.position="none")


Legend1 <- 
    data2 %>%
    filter(Item %in% c("Bag","Wallet","Shoes")) %>%
    ggplot(aes(x=Year,fill=Item))+geom_bar()+
    scale_fill_manual(values=palette1,name="Accessories")

Legend2 <- 
    data2 %>%
    filter(Item %in% c("Shirt","Flower","Bees")) %>%
    ggplot(aes(x=Year,fill=Item))+geom_bar()+
    scale_fill_manual(values=palette2,name="Not Accessories")


plot_grid(
    full_plot
    , plot_grid(
      get_legend(Legend1)
      , get_legend(Legend2)
      , nrow = 2
    )
    , nrow = 1
    , rel_heights = c(1,0)

  )




Solution

  • Use this plot_grid call:

    Leg <- plot_grid(get_legend(Legend1), get_legend(Legend2), nrow = 4, align = "hv")
    plot_grid(full_plot, Leg)
    

    screenshot