Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 打印到由函数创建的打印设备_R_Pdf_Plot - Fatal编程技术网

R 打印到由函数创建的打印设备

R 打印到由函数创建的打印设备,r,pdf,plot,R,Pdf,Plot,我想使用函数打开并命名一个pdf绘图设备;在调用设备打开功能的级别对其进行绘图;然后使用该级别提供的dev.off()命令关闭它--这在R中可能吗 背景 我按要求从R打印a到pdf,因此做了很多工作: pdf(file.path(plotPATH, pdfName), width = Wwidth, height = Hheight) plot( ...) dev.off() 为了提高懒散感,我创建了一个函数来打开绘图设备并保存pdf(file.path(plotPATH…)样板文件 我创建的

我想使用函数打开并命名一个
pdf
绘图设备;在调用设备打开功能的级别对其进行绘图;然后使用该级别提供的
dev.off()
命令关闭它--这在
R
中可能吗

背景

我按要求从R打印a到
pdf
,因此做了很多工作:

pdf(file.path(plotPATH, pdfName), width = Wwidth, height = Hheight)
plot( ...)
dev.off()
为了提高懒散感,我创建了一个函数来打开绘图设备并保存
pdf(file.path(plotPATH…)
样板文件

我创建的函数是:

pdfMk <- function(pdfName, Wwidth = 480, Hheight = 480) 
{ 
    pdf(file.path(plotPATH, pdfName), width = Wwidth, height = Hheight)
}
问题是这不起作用。。。输出是具有适当名称和适当位置的
pdf
,但始终为空

我想我可能在闭包(或其他方面)方面有问题,所以我尝试使用
debug
单步执行
pdfMk
函数,并在函数调用结束前创建绘图,但输出仍然是一个空白pdf(在这两种情况下都没有错误消息)


这可能吗?如果是,我该如何实现我的目标

除了默认值之外,您的代码按预期工作

?pdf

宽度,高度:图形区域的宽度和高度,以英寸为单位。默认值为7


您正在创建一个大小为40 x 40英尺的文档。

只是出于好奇:为什么不在函数中包含绘图和
dev.off()
? 差不多

plotpath=file.path("C:","temp")

pdf_wrapper=function(plot_expression,pdfName,plotpath,Wwidth=7,Hheight=7) {
    pdf(file.path(plotpath,pdfName),width=Wwidth,height=Hheight)
    plot_expression
    dev.off()
    Sys.sleep(0.5)
}

pdf_wrapper(plot(c(1,2),c(1,2),type='l',col='blue',lty=2),"test.pdf",plotpath)

顺便说一句:在这种情况下,我总是在末尾包含
Sys.sleep(…)
。如果后续调用了
pdf\u wrapper
,这将非常有用。我不知道这是因为R还是RStudio,但有时我会在不包括等待时间的情况下收到损坏的pdf文件。这似乎可以确保有足够的时间来正确转动设备。但是,我使用的是
ggplot2
,对于
graphics::plot
,这可能不是问题。

非常感谢,我错过了这个细节,有点尴尬。+1,谢谢。好提示。
plot\u表达式
有时很混乱,但这是我的代码的一个问题,您的建议是改善这种情况的一个很好的理由。
plotpath=file.path("C:","temp")

pdf_wrapper=function(plot_expression,pdfName,plotpath,Wwidth=7,Hheight=7) {
    pdf(file.path(plotpath,pdfName),width=Wwidth,height=Hheight)
    plot_expression
    dev.off()
    Sys.sleep(0.5)
}

pdf_wrapper(plot(c(1,2),c(1,2),type='l',col='blue',lty=2),"test.pdf",plotpath)