Rscript is plotting to PDF
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 <-开发者_Go百科 1:10
y <- sin(x)
plot(x,y)
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.
Using windows, I worked around this issue by writing a batch script that calls Rscript on the script, then immediately opens the generated PDF.
@echo off
rscript myscript.r
Rplots.pdf
Although this solution is ridiculous, it is exactly what I needed, which is simply viewing the plotted data on the fly.
精彩评论