2

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

rez
  • 290
  • 2
  • 12
  • 1
    This is happening because of your long legend name. You can visit [Center-align legend title and legend keys in ggplot2 for long legend titles](https://stackoverflow.com/questions/48000292/center-align-legend-title-and-legend-keys-in-ggplot2-for-long-legend-titles) – UseR10085 Jul 28 '23 at 04:21
  • It works for long titles if you break it like ```"A fairly long legend title \njust for illustration!!!!"``` – UseR10085 Jul 28 '23 at 04:27
  • 6
    The legend box _is_ aligned in the center of your plot. The legend _key_ (i.e. the colorbar) is not; it is drawn from the left edge of the legend background to whatever size you stipulated. If its length is less than the length of the text string, the text string will determine the width of the legend background, and no hjust or alignment will affect it, since it has no room to move. Meanwhile, the legend key will always appear to the left of the text. As far as I can see, the only solutions here are making your bar longer, your text multi-line, or doing some grob hacking. – Allan Cameron Jul 31 '23 at 12:03

0 Answers0