我在 R session 中保存的图形和图表通常用于我的文档,我想用工作目录、文件名和日期对它们进行注释。由于我需要硬拷贝我的文档(不要问),这会让我的生活更轻松。我想我可以在打印之前修改 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 )
}
虽然它与我通常生成的绘图配合得相当好,但也许已经有更好的解决方案 OOB 了?或者,也许上面的脚本可以改进?
最佳答案
编写自己的函数来包装 dev.copy2pdf
是个好主意,我认为您正在努力解决这个问题。查看函数 mtext
和 title
以了解在页边距中放置文本的不同方法。如果这些不能完全满足您的要求,请在设置 par(xpd=NA)< 后将
。在所有情况下,您可能希望使用 grconvertX
和 grconvertY
与 text
一起使用adj
参数来指定调整,而不是计算字符串宽度和高度并将值移动一半。
关于r - 在 R 中,如何自动注释每个保存的图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17294173/