2014-10-30 68 views
6

我想添加一個.png圖像(標誌)到我的pdf格式報告的圖形使用ggplot創建並打印到PDF的標題。添加圖像(PNG文件)到用R創建的pdf文件的標題

我發現以下示例如何將圖像添加到ggplot圖。但是,我正在尋找將.png圖像添加到位於ggplot區域之外的pdf標題。

#------------------------------------------------------------------------------- 
# 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() 

...其產生的PDF格式,看起來像這樣:

enter image description here

但是,我想形象展現出來的ggplot區域之外。或者更具體地說,我希望圖像在報告標題中顯示(在左上角),如下面的例子:

enter image description here

我發現下面的功能,可用於創建文本的註腳,但WASN不知道如何修改它來插入.png圖片。

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() 
    } 

任何援助將不勝感激。

+0

你用乳膠或降價?如果是的話,那麼你可以使用'wallpaper'包裝:'\ ULCornerWallPaper {1} {path/to/logo}; \ includegraphics {path/to/ggplot/image}' – tonytonov 2014-10-30 07:29:03

+0

@Tonytonv:謝謝您的回覆。爲了澄清,我的圖像不是ggplot的產品,而是保存的圖像(即.png文件)。我會看看乳膠和降價,但認爲應該有一個簡單的方法來做到這一點與基本圖形。不幸的是,我已經走了ggplot路線,所以我不熟悉基礎圖形。再次感謝您的建議。 – MikeTP 2014-10-30 15:29:01

+0

請注意,PDF規範不支持PNG。因此,在插入之前,您的PNG將被轉換爲其他內容,可能是JPEG。我建議你自己做這種轉換,以你想要的格式,以你想要的質量進行,這樣你就可以確定最終產品的質量。我會推薦JPEG2000。 – Alasdair 2014-11-16 18:02:42

回答

10

這裏有一個建議,

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

+0

這是在標題上面打印圖像(添加'實驗室(標題= ...)')時,所以它在繪圖頂部消耗更多空間。即這不是OP要求的'報告標題'。 – 2017-09-27 08:10:08