简体   繁体   中英

Automatically calling dev.off after plot in R

I'm looking for a way to automatically call dev.off() to flush a plot to disk when someone calls plot() or ggplot().

Is this possible? RStudio looks to automatically load the plot, how does that work?

Edit: Add possible approach for ggplot .

Note that the reason that plot , in particular, doesn't automatically call dev.off() is that it's very common -- after calling plot -- to add additional material (annotations, supplementary plotting features, titles, legends, etc.) with additional calls before calling dev.off() to finalize the output.

But, if you really want plot to finalize the plot and prevent any further content from being added, you can do it by redefining plot :

plot <- function(...) {
    graphics::plot(...)
    dev.off()
}

Note that for window-based graphics devices (eg, x11 ), the plot will briefly flash on the screen before disappearing, since dev.off() closes the window, but it should work fine for files:

> png("plot.png")
> plot(1:10,runif(10))
null device     <-- proof that dev.off() was called
          1 
> 

For ggplot2 , I guess your best bet is to override the print method (which is how a plot normally gets displayed on the screen). So, if you define:

print.ggplot <- function(...) {
    ggplot2:::print.ggplot(...)
    dev.off()
}

then:

> png("plot.png")
> ggplot(mapping=aes(x=1:10,y=1:10))+geom_line()
[[ print method is implicitly called here ]]
> dev.off()   # to prove that dev.off() was already called
Error in dev.off() : cannel shut down device 1 (the null device)
>

appears to work the way you want.

I don't use RStudio, so I'm not sure what it's doing differently, but I'm going to guess that it intercepts the graphics commands in such a way that it simultaneously shows the "plot in progress" before the file is finalized, rather than actually displaying the file (which, for bitmapped graphics, can't be written out at all until the plot is completely finished and dev.off() is called).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM