How to save a plot as image on the disk?

后端 未结 11 1289
失恋的感觉
失恋的感觉 2020-11-22 10:38

I plot a simple linear regression using R. I would like to save that image as PNG or JPEG, is it possible to do it automatically? (via code)

There are two different

11条回答
  •  面向向阳花
    2020-11-22 10:59

    In some cases one wants to both save and print a base r plot. I spent a bit of time and came up with this utility function:

    x = 1:10
    
    basesave = function(expr, filename, print=T) {
      #extension
      exten = stringr::str_match(filename, "\\.(\\w+)$")[, 2]
    
      switch(exten,
             png = {
               png(filename)
               eval(expr, envir = parent.frame())
               dev.off()
             },
             {stop("filetype not recognized")})
    
    
      #print?
      if (print) eval(expr, envir = parent.frame())
    
      invisible(NULL)
    }
    
    #plots, but doesn't save
    plot(x)
    
    #saves, but doesn't plot
    png("test.png")
    plot(x)
    dev.off()
    
    #both
    basesave(quote(plot(x)), "test.png")
    
    #works with pipe too
    quote(plot(x)) %>% basesave("test.png")
    

    Note that one must use quote, otherwise the plot(x) call is run in the global environment and NULL gets passed to basesave().

提交回复
热议问题