首页 > 解决方案 > 自定义R中常见图例的位置

问题描述

我需要在一个页面中安排多个带有共同图例的图,并使用以下代码:

library(ggpubr)
ggarrange(fig1, fig2, fig3, nrow=2, ncol=2, common.legend = TRUE, legend="right")

现在,我想知道是否还有其他包/方式可以自定义常见图例的位置,因为“ggarrange”只有“顶部”、“底部”、“右”、“左”和“无”选项这个。由于第二行和第二列是空的,我希望图例出现在那里。

标签: rggplot2ggpubr

解决方案


也许cowplot 包会起作用?

最小可重现示例:

library(tidyverse)
library(ggpubr)

fig1 <- ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point()
fig2 <- ggplot(mtcars, aes(x = cyl, y = mpg, group = cyl, fill = factor(cyl))) +
  geom_boxplot() +
  scale_fill_viridis_d()
fig3 <- ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point()

ggarrange(fig1, fig2, fig3, nrow=2, ncol=2, common.legend = TRUE, legend="right")

示例_1.png

使用 cowplot 包:

library(cowplot)
legend <- get_legend(fig2)
fig2_no_legend <- ggplot(mtcars, aes(x = cyl, y = mpg, group = cyl, fill = factor(cyl))) +
  geom_boxplot() +
  scale_fill_viridis_d() +
  theme(legend.position = "none")

cowplot::plot_grid(fig1, fig2_no_legend, fig3, legend, nrow = 2, ncol = 2)

示例_2.png


推荐阅读