我写了一个创建条形图的函数.我想将这个图保存为pdf,并在应用此功能时将其显示在我的屏幕(x11)上.代码看起来像这样.
create.barplots <- function(vec)
{
x11() # opens the window
### Here is a code that creates a barplot and works perfectly
### but irrelevant for my question
dev.copy(pdf("barplots.table.2.pdf")) # is supposed to copy the plot in pdf
# under the name "barplots.table.2.pdf"
dev.off() # is supposed to close the pdf device
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下错误:'device'应该是一个函数
当我将代码修改为:
create.barplots <- function(vec)
{
x11()
### Here is a code that creates a barplot and works perfectly
### but irrelevant for my question
dev.copy(pdf) # This is the only difference to the code above
dev.off()
}
Run Code Online (Sandbox Code Playgroud)
R显示绘图并创建一个名为Rplots.pdf的文件.由于几个原因,这是一个问题.
我还试图以相反的方式打开设备.首先打开pdf设备,而不是将pdf设备的内容复制到x11设备,而不是将pdf设备设置为活动设备,而不是关闭pdf设备.这里的代码如下所示:
create.barplots <- function(vec)
{
pdf("barplots.table.2.pdf") # open the pdf device
### Here is a code that creates a barplot and works perfectly
### but irrelevant for my question
dev.copy(x11) # copy the content of the pdf device into the x11 device
dev.set(which = 2) # set the pdf device as actice
dev.off() # close the pdf device
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是应该显示情节的wondow是空的!
总而言之,我有两个问题:1)如何将图表保存为pdf并同时在x11中显示?2)如何将绘图保存在其他地方的工作目录中?
编辑
上述解决方案效果很好.但我仍然不明白为什么
pdf("barplots.table.2")
barplot(something)
dev.copy(x11)
Run Code Online (Sandbox Code Playgroud)
显示一个空的灰色窗口,而不是在窗口设备中复制pdf设备的内容!我也试过了
pdf("barplots.table.2")
barplot(something)
dev.copy(window)
Run Code Online (Sandbox Code Playgroud)
其中我也失败了......
Max*_*ner 25
怎么样:
create.barplots <- function(...) {
x11()
plot.barplots(...) # create the barplot
dev.copy2pdf(file = "path/to/barplots.table.2.pdf")
}
Run Code Online (Sandbox Code Playgroud)
您可以pdf
在dev.copy
调用中轻松添加参数,如下所示:
create.barplots <- function(vec,dir,file)
{
windows()
plot(vec)
dev.copy(pdf,file=paste(dir,file,sep="/")
dev.off()
}
Run Code Online (Sandbox Code Playgroud)
dev.copy()
有一个...参数传递参数到pdf函数,请参阅?dev.copy
.或者你可以使用dev.copy2pdf
,正如马克斯告诉你的那样.我还建议您使用windows()
而不是x11()
,否则您可能会遇到字体系列的问题.x11和pdf的默认值并不总是匹配.
要将文件保存在另一个目录中,只需添加完整目录(例如,使用粘贴,就像上面的函数一样)