首页 > 解决方案 > 对齐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 将图例置于左图下方。有没有办法让这个共享的图例居中在两个图像之间?

标签: rggplot2cowplot

解决方案


更改theme如下;

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


推荐阅读