Search code examples
rggplot2cairo

Cairo: Why does the Cairo not work in function?


My demo code was like that:

   p <- plot(c(1,3,4,5,6,4,3),c(1,2,3,4,5,6,7))
    myTiff <- function(p){
        tiff("E:/aaa.tiff")
        p
        dev.off()
    }
    myTiff(p)

But its does not work(the image was successfull saved, and the size was not 0 mb, but it cant open), whats wrong with it?


Solution

  • I think the problem is storing the plot in p. Try

    p <- data.frame(x=c(1,3,4,5,6,4,3), y=1:7)
    myTiff <- function(p){
        tiff("E:/aaa.tiff")
        plot(p)
        dev.off()
    }
    myTiff(p)
    

    instead. In this case your function input are the points to be plottet not the stored plot.

    By using ggplot2 there are other ways since a ggplot can be stored:

    df <- data.frame(x=c(1,3,4,5,6,4,3), y=1:7)
    p  <- ggplot(df, aes(x=x, y=y)) + geom_point()
    
    myJpeg <- function(p){ 
      ggsave("E:/test.jpg", p) 
    }