【问题标题】:Add image (png file) to header of pdf file created with R将图像(png 文件)添加到使用 R 创建的 pdf 文件的标题中
【发布时间】:2014-12-26 00:08:41
【问题描述】:

我正在尝试将 .png 图像(徽标)添加到我使用 ggplot 创建并打印到 pdf 的图表的 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:

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

我找到了以下可用于创建文本脚注的函数,但不知道如何修改它以插入 .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()
    }

任何帮助将不胜感激。

【问题讨论】:

  • 你用的是latex还是markdown?如果是,那么您可以像这样使用wallpaper 包:\ULCornerWallPaper{1}{path/to/logo}; \includegraphics{path/to/ggplot/image}
  • @Tonytonv:感谢您的回复。澄清一下,我的图像不是 ggplot 的产品,而是保存的图像(即 .png 文件)。我将看一下乳胶和降价,但认为应该有一种简单的方法来使用基本图形来做到这一点。不幸的是,我走的是 ggplot 路线,所以我不熟悉基本图形。再次感谢您的建议。
  • 请注意,PDF 规范不支持 PNG。因此,在插入之前,您的 PNG 将被转换为其他内容,可能是 JPEG。我建议您以您想要的质量自己将这种转换转换为您想要的格式,这样您就可以确定最终产品的质量。我推荐JPEG2000。

标签: r pdf graphics ggplot2 usergrid


【解决方案1】:

这里有一个建议,

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)

【讨论】:

  • 这是在标题上方打印图像(添加labs(title = ...)时),因此它会占用绘图顶部的更多空间。 IE。这不是 OP 要求的“报告标题”。
猜你喜欢
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多