在排列的图表之间绘制一个“网格”

6

我正在使用 ggpubr 软件包中的 ggarrange() 将 4 个不同的绘图整合到一个单独的绘图中。以下是一个示例:

library(ggpubr)
library(ggplot2)

p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 1")
p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 2")
p3 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 3")
p4 <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 4") +
  facet_wrap(~Species)

plot.list <- list(p1, p2, p3, p4)

ggarrange(plotlist = plot.list)

输出:

输出:

在这里输入图片描述

我想在每个绘图区域周围画一个边框,像这样:

在这里输入图片描述

有没有办法画出这个边框?谢谢!

2个回答

5

不确定这对你是否有用,但你可以给每个图形加边框。然而,这将包括布局外部的边框。从你的描述来看,似乎你并不反对这样做,但是在你的示例图中,只有内部网格线。

创建图时,您可以添加theme调用;而不是编辑图的创建,我只是在将所有图粘在一起之前将其应用于列表中的每个图。

library(ggpubr)
library(ggplot2)

#### same plot creation here ######

plot.list <- lapply(list(p1, p2, p3, p4), 
                    function(p) p + theme(plot.background = element_rect(color = "black")))

ggarrange(plotlist = plot.list)


1
我认为Carles上面给出的答案最好地回答了OP所问的问题! - mnm

5

grid.polygon()相当于手工操作,但我认为它能完成任务:

使用RStudio

library("ggpubr")
library(ggplot2)
library(gridExtra)
library(grid)
p1 <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 1")
p2 <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 2")
p3 <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Width)) + geom_point() + ggtitle("Plot 3")
p4 <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Width)) + geom_point() + ggtitle("Plot 4") +
  facet_wrap(~Species)

plot.list <- list(p1, p2, p3, p4)

ggarrange(plotlist = plot.list)
x = c(0, 0.5, 1, 0.5, 0.5, 0.5)
y = c(0.5, 0.5, 0.5,0, 0.5, 1)
id = c(1,1,1,2,2,2)
grid.polygon(x,y,id)

在此输入图片描述 使用 Shiny(编辑)

当在 Shiny 应用程序内进行操作时,需要使用 annotation_custom() 添加网格,如下所示:

    ggarrange(plotlist = plot.list) + 
    annotation_custom(
             grid.polygon(c(0, 0.5, 1, 0.5, 0.5, 0.5),
                          c(0.5, 0.5, 0.5,0, 0.5, 1), 
                          id = c(1,1,1,2,2,2), 
                          gp = gpar(lwd = 1.5)))

只是一个快速的补充,因为我在shiny-app中使用这个图形,所以我必须使用annotation_custom()添加网格,就像这样:ggarrange(plotlist = plot.list) + annotation_custom(grid.polygon(c(0, 0.5, 1, 0.5, 0.5, 0.5), c(0.5, 0.5, 0.5,0, 0.5, 1), id = c(1,1,1,2,2,2), gp = gpar(lwd = 1.5))) - brettljausn
@brettljausn,我在解释中加入了你的观点。谢谢! - Carles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接