Adding a logo to multi-line output in R or ggplot2

I am trying to add a logo to the output obtained from grid.arrange or arrGrob.

I have the code below:

Library (ggplot2)

p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
         geom_line() +
         ggtitle("Growth curve for individual chicks")

 p2 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet)) +
          geom_point(alpha=.3) +
           geom_smooth(alpha=.2, size=1) +
          ggtitle("Fitted growth curve per diet")

 p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet))         
          + geom_density() +
          ggtitle("Final weight, by diet")

 p4 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, fill=Diet)) +
         geom_histogram(colour="black", binwidth=50) +
         ggtitle("Final weight, by diet") 

I used grid.arrange (p1, p2, p3, p4, ncol = 2, clip = 4) to put several graphs in one graph.

But I had a problem inserting the logo into the output grid.arrange file.

I tried the method below, but received the following error message.

    b <- rasterGrob(img, width=unit(5,"cm"), x = unit(40,"cm")) 
     z1 <- ggplotGrob(grid.arrange(p1,p2,p3,p4,ncol=2,clip=4)) 
     z1<- gtable_add_grob(z1,b, t=1,l=1, r=5)
     grid.newpage()
      grid.draw(z1)

Error: no layers in plot

Is there a way or way to add a logo to the output after organizing a Grob or grid.arrange.

+2
source share
1 answer

Not an answer gtable, but this is a slightly different way to add a logo that might help.

library(ggplot2)
library(grid)
library(png)
library(gridExtra)

# Read png
img <- readPNG(system.file("img", "Rlogo.png", package="png"), FALSE)

# Create grobs to add to plot
my_g <- grobTree(rectGrob(gp=gpar(fill="black")),
                 textGrob("Some text", x=0, hjust=0, gp=gpar(col="white")),
                 rasterGrob(img, x=1, hjust=1))

# Plot
p <- ggplot(mtcars , aes(wt , mpg)) + 
           geom_line() +
           theme(plot.margin=unit(c(1, 1, 1,1), "cm"))

# Add as a strip along top
grid.arrange(my_g, arrangeGrob(p,p,p,p, ncol=2), heights=c(1, 9))

enter image description here

+2
source

Source: https://habr.com/ru/post/1616901/


All Articles