Ben
Ben

Reputation: 509

Show ggplot graphs in new window by default with X11

I'm on Ubuntu 18.04 using RStudio 1.4. I use the external device X11 to see graphics because I often need to have multiple plots shown at a time. I would like to have ggplot show each plot in a new device by default, as if a ggplot call was always preceded by a call to dev.new(). I'm fine with having to do a bunch of manual window closing. Is there a way to have that default behavior? Below is a MWE.

library(tidyverse)
options(device = "X11")

# regular default behavior, where a new ggplot call will overwrite the plot in the active device (if any)
mtcars %>% 
  ggplot(aes(x = cyl, y = mpg)) + 
  geom_point()

# desired default behavior, where a new device is created with the ggplot call
dev.new(); mtcars %>% 
  ggplot(aes(x = cyl, y = mpg)) + 
  geom_point()

Upvotes: 1

Views: 1010

Answers (1)

Ben
Ben

Reputation: 509

I found a simple way by overriding the ggplot print method:

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

You can either save the old method in a variable to restore it within the current session, or restart the R session to restore defaults. A similar approach should work for a lot of other graphics packages.

Upvotes: 1

Related Questions