I've a simple R script. When it is run via Rscript.exe, by default it is plotting to a PDF file. I want the script to open a plot window.
I using the command:
Rscript.exe tmp_plot.R
r file tmp_plot.R contains:
x <- 1:10
y <- sin(x)
plot(x,y)
Plot the data frame with 'o' and 'rx' style. To save the file in PDF format, use savefig() method where the image name is myImagePDF. pdf, format = ”pdf”. To show the image, use the plt.
Under Windows, right click inside the graph window, and choose either "Save as metafile ..." or "Save as postscript ..." If using Word, make sure to save as a metafile.
Save Multiple Plots to Same Page in PDF: To save multiple plots to the same page in the PDF file, we use the par() function to create a grid and then add plots to the grid. In this way, all the plots are saved on the same page of the pdf file. We use the mfrow argument to the par() function to create the desired grid.
You are running R in a non-interactive way - Rscript is meant for scripts - hence the default plotting device is pdf()
, not x11()
or whatever is your OS's default (windows()
by the looks of it). It is trivial to open an alternative device, however; use x11()
or windows()
. The problem you have in trying to write a script that will display a plot on screen is that, in your example code shown, the script terminates immediately upon drawing the plot, whether displayed on screen or on the pdf()
device. At best you might get it to pause using Sys.sleep()
, e.g.:
x <- 1:10
y <- sin(x)
x11() ## or windows()
plot(x,y)
Sys.sleep(10)
I think you are going about this the wrong way. If you want interactivity when running an R "script", by which I mean a set of R statements that perform some analysis, you'd be better off getting an editor/IDE on your OS that allows you to step through the script a line or chunk of code at a time, plus interact with the running R session. I use Emacs and the ESS extension for this. You might consider Tinn-R or RStudio as alternatives.
Rscript
is meant for running scripting or batch-like jobs that do not need human interaction or intervention.
library(tcltk) # for message box and thus hold-open functionality
x11() # for Linux, see documentation for other operating systems
# first plot
# second plot
# hold-open functionality prevents script from exiting user acts
prompt <- "hit spacebar to close plots"
extra <- "some extra comment"
capture <- tk_messageBox(message = prompt, detail = extra)
If you don't like the idea of a prescribed timer, the above script will only exit on key press (the spacebar or enter) or mouse click (the OK button) from the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With