将图像(png 文件)添加到用 R 创建的 pdf 文件的标题 [英] Add image (png file) to header of pdf file created with R

查看:22
本文介绍了将图像(png 文件)添加到用 R 创建的 pdf 文件的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 .png 图像(徽标)添加到我使用 ggplot 创建并打印为 pdf 的图表的 pdf 报告的标题中.

I am trying to add an .png image (logo) to the header of my pdf report of graphs created with ggplot and printed to pdf.

我发现以下示例如何将图像添加到 ggplot 绘图.但是,我希望将 .png 图像添加到 ggplot 区域之外的 pdf 标题中.

I found the following example how to add a image to a ggplot plot. But, I am looking to add the .png image to he header of the pdf 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()

...生成的 pdf 如下所示:

...which produces a pdf that looks like this:

但是,我希望图像显示在 ggplot 区域之外.或者更具体地说,我希望图像显示在报告标题(左上角)中,如下例所示:

But, I would like the image to show up outside the ggplot area. Or more specifically, I want the image to show up in the report header (in upper left) like the following example:

我发现以下函数可用于创建文本脚注,但不确定如何修改它以插入 .png 图像.

I found the following function that can be used to create a text footnote but wasn't sure how to modify 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()
    }

任何帮助将不胜感激.

推荐答案

这里有一个建议,

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)

这篇关于将图像(png 文件)添加到用 R 创建的 pdf 文件的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆