5

I'm new to R and trying to show graphs and images on the same page with R. I tried to use library(ggpubr) and ggarrange() function.

to import the images I used library(png) and readPNG() to import my images.

The end result i'm aiming for is something like this:

enter image description here

The code i used to create the panel is:

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)

of curse i inserted the images manually using power-point.

Thanks,

loki
  • 9,816
  • 7
  • 56
  • 82

1 Answers1

3

I think your code is almost there. If you use the theme function to add some margins you can get something like this:enter image description here

Code below. The only addition is theme(plot.margin = margin(t=1, l=1, r=1, b=1, unit = "cm")) for both images.

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)
Vandenman
  • 3,046
  • 20
  • 33