Using long legend name in scale_fill_gradientn cause legend box to be off-centered, and more when use with cowplot functions ggdraw and draw_plot

107 views Asked by At

I wonder how could I fix the position of my legend box in the bottom-middle of my map, specifically when I using inset plot with cowplot functions. I tried various ways but it didn’t work. Would appreciate any help on this.

Here is a reproducible example:

library(ggplot2)
library(dplyr)
library(sf)
library(cowplot)

nc <- st_read(system.file("shape/nc.shp", package="sf"))

mainplot <- nc %>% 
  ggplot() + 
  geom_sf(aes(fill = AREA)) + 
  scale_fill_gradientn(name="A fairly long legend title just for illustration!!!!",
                       colors = RColorBrewer::brewer.pal(9, "Spectral") %>% rev()) +
  
  guides(fill = guide_colorbar(title.position = "top", title.hjust = 0.5, 
                               barwidth = 8, barheight = 1)) +

  theme(legend.direction = "horizontal", legend.position = "bottom")

histplot <- nc %>% ggplot() + geom_histogram(aes(AREA))

ggdraw(mainplot) +
  draw_plot(histplot + theme_cowplot(12), .04, .25, .25, .2)

enter image description here

0

There are 0 answers