在R中,如何自动注释保存的每个图形?

在R中,如何自动注释保存的每个图形?,r,pdf,graph,annotations,R,Pdf,Graph,Annotations,我在R会话中保存的图形和图表通常用于我的文档,我想用工作目录、文件名和日期对它们进行注释。因为我需要硬拷贝我的文档(不要问),这会让我的生活更轻松。我想我可以在打印之前修改pdf,但实际上我更喜欢将数字直接印在R上 由于大多数时候我都是使用dev.copy2pdf()生成图形,因此我设计了以下小功能: # annotate PDF copy of the graph produced copyan <- function( file= "tmp.pdf", cex= 0.75 ) {

我在R会话中保存的图形和图表通常用于我的文档,我想用工作目录、文件名和日期对它们进行注释。因为我需要硬拷贝我的文档(不要问),这会让我的生活更轻松。我想我可以在打印之前修改pdf,但实际上我更喜欢将数字直接印在R上

由于大多数时候我都是使用
dev.copy2pdf()
生成图形,因此我设计了以下小功能:

# annotate PDF copy of the graph produced
copyan <- function( file= "tmp.pdf", cex= 0.75 ) {

  oldpar <- par( mar= c( 0, 0, 0, 0 ), usr= c( 0, 1, 0, 1 ) )
  on.exit( par( oldpar ) )

  par( new= TRUE )
  plot.new()

  # ann is the annotation stamp:
  # current working directory,
  # file name, date and time.
  ann <- paste( getwd(), file, Sys.time(), sep= ", " )
  strh <- strheight( ann, cex= cex )
  strw <- strwidth(  ann, cex= cex )

  # put text in the lower bottom corner,
  # just at the very margin of the plot
  usr1 <- par( "usr" )
  text( usr1[1] + strw/2, usr1[3] + strh/2, ann, cex= cex )

  dev.copy2pdf( file= file )
}
#注释生成的图形的PDF副本

copyan编写自己的函数包装
dev.copy2pdf
是一个好主意,我认为您已经走了很长的路。查看函数
mtext
title
,了解在页边距中放置文本的不同方式。如果这些不能完全满足您的要求,则在设置
par(xpd=NA)
后,将
grconvertX
grconvertY
text
一起使用。在所有情况下,您都可能希望使用
adj
参数来指定调整,而不是计算字符串的宽度和高度以及移动值的一半

library(gridExtra)
library(ggplot2)

p <- qplot(1, 1)

stamp <- paste("Data: Monday 24 June 2013", 
               strftime(Sys.time(), "Plotted: %A %d %B %Y @%H:%M"), 
               sep="\n")

grid.arrange(p, sub=textGrob(stamp, gp=gpar(cex=0.8, col="grey"), 
                             hjust=1, vjust=0, x=1))
库(gridExtra)
图书馆(GG2)

p如果你在你想要的绘图位置得到你想要的注释,为什么要改变任何东西?:-)。也许你可以把它变成一个函数,只是为了让它更容易在N个图形上循环,等等。我做到了(这是我的“我每天都需要的方便的小工具”包的一部分,我总是在我工作的地方安装它)。