Saving dotplot to pdf in R [duplicate]

巧了我就是萌 提交于 2020-01-13 16:53:11

问题


I am having trouble saving a dotplot to pdf when this command is done inside a function.

It works fine when called normally:

df <- data.frame(a = runif(10), b = runif(10), c = runif(10), x = 1:10)  
pdf("test.pdf")  
dotplot(a + b + c ~ x, data = df, type = "l", auto.key=TRUE)  
dev.off()

But if this code is inside a function, it will not work and just makes an empty or blank file:

plotFunc <- function(model)  
{  
    pdf("test.pdf")  
    dotplot(a + b + c ~ x, data = model, type = "l", auto.key=TRUE)  
    dev.off()  
}
plotFunc(df)

However, calling the function without the file commands will successfully print to the graphics window:

plotWinFunc <- function(model)  
{  
    dotplot(a + b + c ~ x, data = model, type = "l", auto.key=TRUE)  
}  
plotWinFunc(df)

This leads me to believe that something goes wrong with dotplot() when it is supposed to output to a file. And the type of file doesn't matter, I have tried with both bmp and pdf and neither method works.

How can I successfully write a dotplot to a file? Do I have to use a special command from the lattice package or do I have an error somewhere?

Thanks for any help.


回答1:


Just realized I have to wrap dotplot in print():

plotFunc <- function(model)    
{    
    pdf("test.pdf")    
    print(dotplot(a + b + c ~ x, data = model, type = "l", auto.key=TRUE))    
    dev.off()    
}  
plotFunc(df)

That seems to have solved it.



来源:https://stackoverflow.com/questions/2277166/saving-dotplot-to-pdf-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!