如何使用grid.arrange将图例放在右侧?

bkhjykvo  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(87)

我如何让4个图以2x2的模式显示,没有图例,然后放置在最右边,居中在第1行和第2行之间。所以在第三列可以这么说。

a=mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")
b=mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")
c=mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")
d=mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")

grid.arrange(a, b, c ,d, ncol = 2)

搜索了Web和堆栈

p8h8hvxi

p8h8hvxi1#

更新见OP请求:
只需在grid.arrange()中更改widths,如下所示:

.....
# Arrange the plots
grid.arrange(
  arrangeGrob(a, b, c, d, ncol = 2),
  legend,
  ncol = 3,
  widths = c(8, 2, 0)  # Adjust to desired proportions
)


第一个答案:我们可以使用gridExtracowplot包来实现:

library(ggplot2)
library(gridExtra)
library(cowplot)

# Create the 4 plots without a legend
a <- mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey") +
  theme(legend.position = "none")

b <- mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")  +
  theme(legend.position = "none")

c <- mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")  +
  theme(legend.position = "none")

d <- mtcars %>%
  ggplot(aes(x = disp, y = mpg, colour=hp)) +
  geom_point(size=2) +
  geom_smooth(se=F, colour="grey")  +
  theme(legend.position = "none")

# Create a separate legend
legend <- get_legend(
  mtcars %>%
    ggplot(aes(x = disp, y = mpg, colour=hp)) +
    geom_point(size=2) +
    geom_smooth(se=F, colour="grey"))

# Arrange the plots
grid.arrange(
  arrangeGrob(a, b, c, d, ncol = 2),
  legend,
  ncol = 3,
  widths = c(4, 4, 1)  # Adjust to desired proportions
)

相关问题