user673592
user673592

Reputation: 2120

R: Show plot when running script from command line

How to display a window with a ggplot figure when executing an R script from the command line (without intermediary save to file)?

Example script test.R

#!/usr/bin/env Rscript

library(ggplot2)
p = ggplot(aes(x = Sepal.Length), data = iris) + geom_histogram(color = 'black', fill = NA)
plot(p)

On the command line run the script with ./test.R. This dumps the plot to Rplots.pdf - instead I'd like a window just like in an interactive session with the plot, with no file output.

How to specify output device to be the screen? (e.g. on Ubuntu)

Upvotes: 7

Views: 5657

Answers (1)

duckmayr
duckmayr

Reputation: 16920

You can do this via a call to X11(), which will open a graphics window. Some relevant excerpts from help("X11"):

on Unix-alikes ‘X11’ starts a graphics device driver for the X Window System (version 11). This can only be done on machines/accounts that have access to an X server.

Usage:

X11(display = "", width, height, pointsize, gamma, bg, canvas, fonts, family, xpos, ypos, title, type, antialias)

Arguments:

display: the display on which the graphics window will appear. The default is to use the value in the user's environment variable ‘DISPLAY’. This is ignored (with a warning) if an X11 device is already open on another display.

However, it will close immediately after the R script is done being executed. So, this works to display your plot, but it isn't open for long:

#!/usr/bin/env Rscript

library(ggplot2)
p = ggplot(aes(x = Sepal.Length), data = iris) +
    geom_histogram(color = 'black', fill = NA)
X11()
plot(p)

I guess the real questions are

  • Why are you averse to saving the plot before viewing it? and
  • If you want to open a plot window but not save the plot, why not just run your commands in an interactive R session? That seems to me more useful if you're not saving results.

Upvotes: 4

Related Questions