tags:

views:

285

answers:

1

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.

+4  A: 

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.

Jared
Yup, it's a FAQ.
Dirk Eddelbuettel
I think you can also wrap it in plot()
Tal Galili
Yeah, I found it right after I posted the question. Somewhere in the help file either for dotplot or lattice.
Jared