Example 1: Pop up the graphics window directly from Rscript using tcltk
Edit from 6 years in the future: tcltk used to be the standard for R display interface but now tcltk
is depreciated. Use Example 2:
library(tcltk) #you have to install tcltk for your OS
x=1:10
y=1:10
windows() #Use X11() or quartz() if on linux or mac.
plot(x,y)
prompt <- "hit spacebar to close plots"
extra <- "some extra comment"
capture <- tk_messageBox(message = prompt, detail = extra)
The above code presents the plot in a popup window and waits for you to press ok on the dialog. If that doesn't work because tcltk
or its interface between R and your screen doesn't work, you can do it manually from your terminal as follows by having R asking the OS to 'open the file for presentation':
Example 2: Pop up the graphics window from Rscript using browseURL
#Tested on R version 4.2.1
png("mygraphic.png") #Create a png file
x = 1:10
print(x^2)
plot(x, x^2, 'o') #Plot x on the horizontal and x^2 on the vertical
print("done")
dev.off()
browseURL("mygraphic.png") #R uses the terminal to tell the
#OS to open mygraphic.png
The above R code saves the png to disk as mygraphic.png
and asks the operating system to open the file in the program designated for that filetype. If it doesn't work open the file manually. To change the program a .png file opens with, has to be done by going to to your OS's system settings which is dependent on your operating system. I make a custom keymapping at the OS level for Alt-w to alt-F4 then I can edit the code, run it, pop the window, dismiss and get back to the editor, all in under 600 milliseconds without touching the mouse.
Example 3: Pop up the graphic using system()
terminal
#Tested on R version 4.2.1
png("mygif.png") #Create a png file
x = 1:10
plot(x, x^5, 'o') #Plot x on the horizontal and x^5 on the vertical
dev.off()
#replace the word 'animate' with your favorite paint/image/gif editor.
system("animate mygif.png") #R uses the terminal to tell the
#OS to open your image/gif
Example 3 is the best. Expecting Rscript to be a display manager is doubleplusungood.