Выровняйте общую легенду в cowplot

#r #ggplot2 #cowplot

Вопрос:

Я собираюсь использовать пакет cowplot, чтобы дать двум ggplots общую легенду. Однако, как я могу центрировать общую легенду, когда есть четное количество сюжетов.

Вот несколько примеров кода:

 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))
 

Который создает это изображение:

введите описание изображения здесь

Как вы можете видеть, cow_plot помещает легенду, расположенную под левым изображением. Есть ли способ сделать эту общую легенду центрированной между двумя изображениями?

Ответ №1:

Измените theme , как показано ниже;

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