Reputation: 2120
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
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
Upvotes: 4