0

I would like to leave my subtitle centered without having to manually change the position by legend.position in theme(). If I select "bottom", the caption will be centered relative to the graphic frame rather than the image, making it necessary to make changes to the margins. Is there any way to center by some argument as in the image?

enter image description here

Igor Cobelo
  • 419
  • 3
  • 12
  • 1
    Though I cannot find them at the moment, this has been asked before (here on SO) and I believe it cannot be done *easily*. The suggested solutions typically end up using `grid` techniques and/or editing the grobs manually, both tend to be a little advanced (and I do now know off-hand how to do it). – r2evans Dec 26 '19 at 00:19
  • 1
    I found a similar question: https://stackoverflow.com/questions/25100038/ggplot2-center-legend-below-plot-instead-of-panel-area?rq=1 – Igor Cobelo Dec 26 '19 at 01:10

1 Answers1

4

You will have to use a workaround such as extracting the legend then combine it with the original plot. Here is an example using get_legend and plot_grid functions from the cowplot package.

library(ggplot2)
library(cowplot)
#> 
#> ********************************************************
#> Note: As of version 1.0.0, cowplot does not change the
#>   default ggplot2 theme anymore. To recover the previous
#>   behavior, execute:
#>   theme_set(theme_cowplot())
#> ********************************************************

p1 <- ggplot(iris, aes(x = Species, y = Petal.Length)) +
  geom_col(aes(fill = Species)) +
  coord_flip() +
  scale_fill_brewer(palette = 'Set2') +
  theme_minimal(base_size = 14) +
  theme(legend.position = 'bottom')

# extract the legend
p1_legend <- get_legend(p1)

# plot p1 and legend together
p2 <- plot_grid(p1 + theme(legend.position = 'none'), p1_legend,
          nrow = 2, rel_heights = c(1, 0.1))

# comparison
plot_grid(p1, p2, 
          nrow = 2)

Created on 2019-12-25 by the reprex package (v0.3.0)

Tung
  • 26,371
  • 7
  • 91
  • 115
  • Hi, Tung! Sorry for the delay in thanking this solution, it worked!! Just a question, if I save an object with ```plot_grid```, I can't add more layers later, like for example ```plot_grid_object + ggtitle("A title")```... Would there be some way to add new layers to the new object? – Igor Cobelo Jun 28 '22 at 20:50
  • Did something change? It looks like the original ggplot centers the legend in the image area so there would no longer be an issue. In fact, it looks like now the plot_grid solution is the one causing the issue of the legend appearing to the left of center. – Cliff Bueno Jun 29 '22 at 06:11