Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R pdf() usage inside a function()

I have some code in R that generates a multipage pdf file:

pdf("myplot.pdf", width=8.5, height=5)

My.Plot(my.data, var1, var2)
My.Plot(my.data, var3, var2)
My.Plot(my.data, var4, var2)

dev.off()

My.Plot() is just a function that parses the necessary data and then uses ggplot to create a graph

The above works just fine. However, when I put this code in a function, there are no plots generated and the output PDF can not be read/opened.

generate.PDF <- function(my.data) {    
    pdf("myplot.pdf", width=8.5, height=5)

    My.Plot(my.data, var1, var2)
    My.Plot(my.data, var3, var2)
    My.Plot(my.data, var4, var2)

    dev.off()
}
like image 957
Ivan P. Avatar asked Oct 10 '13 05:10

Ivan P.


People also ask

What does PDF () do in R?

pdf() opens the file file and the PDF commands needed to plot any graphics requested are sent to that file. The file argument is interpreted as a C integer format as used by sprintf , with integer argument the page number. The default gives files Rplot001. pdf , …, Rplot999.

How do I read a PDF in R?

You can name the function whatever you like e.g Rpdf. The readPDF function has a control argument which we use to pass options to our PDF extraction engine. This has to be in the form of a list, so we wrap our options in the list function. There are two control parameters for the xpdf engine: info and text.


Video Answer


1 Answers

When in a function, you need to call the print() function to actually paint on the canvas, like so:

x <- runif(20,10,20)
y <- runif(20,30,50)
data<-data.frame(x,y)
generate.PDF <- function(data) {    
  pdf("/home/aksel/Downloads/myplot.pdf", width=8.5, height=5,onefile=T)
  plot1 <- plot(x,y)
  plot2 <- plot(y,x)
  plot3 <- plot(x,y*2)
  print(plot1)
  print(plot2)
  print(plot3)
  dev.off()
}
generate.PDF(data)
like image 181
ako Avatar answered Nov 05 '22 08:11

ako