Andrew Dorsey
Andrew Dorsey

Reputation: 83

Align a shared legend in cowplot

I'm looking to use the cowplot package to give two ggplots a shared legend. However, how can I center the shared legend when there's an even number of plots.

Here's some example code:

library(ggplot2)
library(cowplot)
library(rlang)

# down-sampled diamonds data set
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]

# function to create plots
plot_diamonds <- function(xaes) {
  xaes <- enquo(xaes)
  ggplot(dsamp, aes(!!xaes, price, color = clarity)) +
    geom_point() +
    theme_half_open(12) +
    # we set the left and right margins to 0 to remove 
    # unnecessary spacing in the final plot arrangement.
    theme(plot.margin = margin(6, 0, 6, 0))
}

# make two plots
p1 <- plot_diamonds(carat)
p2 <- plot_diamonds(depth) + ylab(NULL)

# arrange the three plots in a single row
prow <- plot_grid(
  p1 + theme(legend.position="none"),
  p2 + theme(legend.position="none"),
  align = 'vh',
  labels = c("A", "B"),
  hjust = -1,
  nrow = 1
)
prow


# extract a legend that is laid out horizontally
legend_b <- get_legend(
  p1 + 
    guides(color = guide_legend(nrow = 1)) +
    theme(legend.position = "bottom")
)

# add the legend underneath the row we made earlier. Give it 10%
# of the height of one plot (via rel_heights).
plot_grid(prow, legend_b, ncol = 1, rel_heights = c(1, .1))

Which produces this image:

enter image description here

As you can see, cow_plot puts the the legend is located underneath the left image. Is there a way to make this shared legend centered between the two images?

Upvotes: 1

Views: 745

Answers (1)

M--
M--

Reputation: 29183

Change the theme like below;

legend_b <- get_legend( p1 + 
                          guides(color = guide_legend(nrow = 1)) +
                          theme(legend.direction = "horizontal",
                                legend.justification="center", 
                                legend.box.just = "bottom")
            )

Upvotes: 3

Related Questions