如何创建要在R中的同一面板上显示的图形和图像

时间:2017-12-17 14:54:58

标签: r ggplot2 ggpubr

我是R的新手并试图用R在同一页面上显示图形和图像。 我尝试使用library(ggpubr)ggarrange()函数。

导入我使用library(png)readPNG()导入图片的图片。

我的目标最终结果是:

enter image description here

我用来创建面板的代码是:

library(ggpubr)
library(png)

data("ToothGrowth")

bxp <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco")
dp <- ggdotplot(ToothGrowth, x = "dose", y = "len",
                color = "dose", palette = "jco", binwidth = 1)

img1 <- readPNG("image1.png")
img2 <- readPNG("image2.png")

im_A <- ggplot() + background_image(img1) # tried to insert the image as background.. there must be a better way
im_B <- ggplot() + background_image(img2) 

ggarrange(im_A, im_B, dp, bxp, 
          labels = c("A", "B", "C", "D"),
          ncol = 2, nrow = 2)
诅咒我使用power-point手动插入图像。

谢谢,

1 个答案:

答案 0 :(得分:1)

我认为你的代码几乎就在那里。如果您使用theme函数添加一些边距,则可以得到如下内容:enter image description here

以下代码。对于两个图像,唯一的添加是theme(plot.margin = margin(t=1, l=1, r=1, b=1, unit = "cm"))

library(ggpubr)
library(png)

data("ToothGrowth")

bxp <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco")
dp <- ggdotplot(ToothGrowth, x = "dose", y = "len",
                color = "dose", palette = "jco", binwidth = 1)

img1 <- readPNG("~/Personal/Wallpapers/375501.png")
img2 <- readPNG("~/Personal/Wallpapers/665150.png")

im_A <- ggplot() + 
    background_image(img1) +
    # This ensures that the image leaves some space at the edges
    theme(plot.margin = margin(t=1, l=1, r=1, b=1, unit = "cm"))

im_B <- ggplot() + background_image(img2) + 
    theme(plot.margin = margin(t=1, l=1, r=1, b=1, unit = "cm"))

ggarrange(im_A, im_B, dp, bxp, 
          labels = c("A", "B", "C", "D"),
          ncol = 2, nrow = 2)