Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving dotplot to pdf in R [duplicate]

Tags:

plot

r

pdf

lattice

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.

like image 608
Jared Avatar asked Feb 17 '26 22:02

Jared


1 Answers

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.

like image 183
Jared Avatar answered Feb 20 '26 13:02

Jared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!