Add image (png file) to the header of a pdf file created with R

I am trying to add a .png image (logo) to the title of my pdf report on graphs created with ggplot and printed in pdf.

I found the following example how to add an image to the ggplot graph . But I want to add a .png image to the pdf header, which is outside the ggplot area.

#------------------------------------------------------------------------------- # Example png file #------------------------------------------------------------------------------- library(reshape2) library(png) mypngfile = download.file('http://api.altmetric.com/donut/502878_64x64.png', destfile = 'mypng.png', mode = 'wb') mypng = readPNG('mypng.png') #------------------------------------------------------------------------------- # create example plot using mtcars data frame from ggplot #------------------------------------------------------------------------------- library(ggplot2) p.example = qplot(mpg, wt, data = mtcars) + annotation_raster(mypng, ymin = 4.5, ymax= 5, xmin = 30, xmax = 35) #------------------------------------------------------------------------------- # print to pdf file with footnote #------------------------------------------------------------------------------- fname = "C:/temp/my report.pdf" pdf(fname, 10.75, 6.5, onefile=TRUE, paper="a4r") print(p.example) dev.off() 

... which creates a pdf file that looks like this:

enter image description here

But I would like the image to be displayed outside the ggplot area . Or, more specifically, I want the image to appear in the title of the report (in the upper left corner), as shown in the following example:

enter image description here

I found the following function that could be used to create a text footnote, but was not sure how to change it to insert a .png image.

  makeFootnote <- function(footnoteText= format(Sys.time(), "%d %b %Y"), size= .4, color= grey(.5)) { require(grid) pushViewport(viewport()) grid.text(label= footnoteText , x = unit(1,"npc") - unit(12, "mm"), y = unit(0.1, "mm"), just=c("right", "bottom"), gp=gpar(cex= size, col=color)) popViewport() } 

Any help would be greatly appreciated.

+6
source share
1 answer

here is the sentence

 library(ggplot2) p.example = qplot(mpg, wt, data = mtcars) library(grid) library(gtable) ann <- rasterGrob(mypng, width=unit(1,"cm"), x = unit(0.5,"cm")) g <- ggplotGrob(p.example) g <- gtable_add_rows(g, grobHeight(ann), 0) g <- gtable_add_grob(g, ann, t=1, l=4) grid.newpage() grid.draw(g) 

enter image description here

+10
source

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


All Articles