Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

r - How to add logo on ggplot2 footer

How to add image logo outside the plotting areas for ggplot2. Tried rasterGrob function from 'grid' package, but that keep's the image inside plot area.

Here is the starter script:

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

gg <- ggplot(df1, aes(x = mpg, y = wt)) + 
       theme_minimal() +
        geom_count() + 
        labs(title = "Title Goes Here", x = "", y = "")

img <- readPNG("fig/logo.png")

Here is the outcome I am looking for.

enter image description here

I can add the annotation on the right side, but the logo on the left is where I am getting challenged.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add the elements with annotation_custom but you need to turn off clipping for the images to show up when they're outside the plot area. I've changed your example slightly in order to make it reproducible.

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

gg <- ggplot(mtcars, aes(x = mpg, y = wt)) + 
  theme_minimal() +
  geom_count() + 
  labs(title = "Title Goes Here", x = "", y = "")

img = readPNG(system.file("img", "Rlogo.png", package="png"))

gg = gg + 
  annotation_custom(rasterGrob(img), 
                    xmin=0.95*min(mtcars$mpg)-1, xmax=0.95*min(mtcars$mpg)+1, 
                    ymin=0.62*min(mtcars$wt)-0.5, ymax=0.62*min(mtcars$wt)+0.5) +
  annotation_custom(textGrob("Footer goes here", gp=gpar(col="blue")), 
                    xmin=max(mtcars$mpg), xmax=max(mtcars$mpg), 
                    ymin=0.6*min(mtcars$wt), ymax=0.6*min(mtcars$wt)) +
  theme(plot.margin=margin(5,5,30,5))

# Turn off clipping
gt <- ggplot_gtable(ggplot_build(gg))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

enter image description here

Another option is to use ggplot's caption feature to add the text footer, which saves some code:

gg = gg + 
  annotation_custom(rasterGrob(img), 
                    xmin=0.95*min(mtcars$mpg)-1, xmax=0.95*min(mtcars$mpg)+1, 
                    ymin=0.62*min(mtcars$wt)-0.5, ymax=0.62*min(mtcars$wt)+0.5) +
  labs(caption="Footer goes here") +
  theme(plot.margin=margin(5,5,15,5),
        plot.caption=element_text(colour="blue", hjust=1.05, size=15)) 

# Turn off clipping
gt <- ggplot_gtable(ggplot_build(gg))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...