R 将绘图另存为pdf并同时在窗口中显示(x11)
我已经编写了一个函数来创建条形图。我想将此绘图保存为pdf格式,并在应用此功能时将其显示在我的屏幕(x11)上。代码如下所示R 将绘图另存为pdf并同时在窗口中显示(x11),r,R,我已经编写了一个函数来创建条形图。我想将此绘图保存为pdf格式,并在应用此功能时将其显示在我的屏幕(x11)上。代码如下所示 create.barplots <- function(vec) { x11() # opens the window ### Here is a code that creates a barplot and works perfectly ### but irrelevant
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
}
显示一个空的灰色窗口,而不是在窗口设备中复制pdf设备的内容!我也试过了
pdf("barplots.table.2")
barplot(something)
dev.copy(window)
我也失败了…那么:
create.barplots <- function(...) {
x11()
plot.barplots(...) # create the barplot
dev.copy2pdf(file = "path/to/barplots.table.2.pdf")
}
create.barplots您可以在dev.copy
调用中轻松添加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
}
create.barplots <- function(vec,dir,file)
{
windows()
plot(vec)
dev.copy(pdf,file=paste(dir,file,sep="/")
dev.off()
}
<代码> CRATATE.BARTROSTS > P>正如我在A中提到的,您可以考虑我的代码> KNITR 包;如果您在交互式R会话中使用它,您将能够在窗口中查看绘图,并将其保存为pdf格式,而无需任何修改(这是默认行为)。我仍然需要在和演示方面做很多工作,但它应该能够与Rnw文档一起工作。您既可以查看绘图,又可以将其保存在knitr
中的主要原因是,knitr
与swave在设计上有很大的不同——图形设备在评估代码后打开,因此您的绘图不会隐藏在屏幕外设备中。同样,我需要提醒您,目前它是高度实验性的。当从内部函数调用时,下面的代码对我来说非常有用。在绘图代码后调用它:
pdf2 <- function (file = "plot.pdf", w = 10, h = 7.07, openPDF = FALSE)
{
dev.copy2pdf(file = file, width = w, height = h, out.type = "pdf")
if(openPDF) browseURL(file)
}
pdf2根据Max Gasner的回答,我编写了这个助手函数,可以快速切换显示和不显示。参数x是绘图对象或绘制图形的函数
savepdf<-function(x, file, display=TRUE) {
if (display){
x;
dev.copy2pdf(file=file)
}
else {
pdf(file=file)
x;
dev.off()
}
}
值得注意的是,几年后,knitr
是最完整的文档包之一。非常感谢@MaxGasner的回答。这真的帮了大忙。我还有一个问题:在现在的输出中,除了成功显示(并保存)的绘图之外,还有一个额外的输出.png
。现在,我必须单击块下的图形,以正确地看到它的全尺寸。有人知道如何去掉.png
以便图形在块下直接满刻度输出吗?我刚刚发现了一个改进:在dev.copy2pdf(file=“path/to/barplots.table.2.pdf”)
行之后添加dev.control(displaylist=“inhibit”)
。.png
输出始终在这里,但现在至少满刻度图是区块下默认显示的输出
pdf2 <- function (file = "plot.pdf", w = 10, h = 7.07, openPDF = FALSE)
{
dev.copy2pdf(file = file, width = w, height = h, out.type = "pdf")
if(openPDF) browseURL(file)
}
savepdf<-function(x, file, display=TRUE) {
if (display){
x;
dev.copy2pdf(file=file)
}
else {
pdf(file=file)
x;
dev.off()
}
}
savepdf(plot(c(1,2,3)), file="123.pdf", display=F)