How to call plot.xts when using RScript
UPDATE: Thanks to Joshua's comment I realized the problem wasn't being inside a function, but inside a script. So I've edited the question and also provided my own answer.
When I use plot.xts() interactively it pops up a graphics window. I just tried it from inside a function (I'm troubleshooting a unit test and wanted some visual help) but nothing appeared. Aha, says I, I know the trick, just use print.
But print(plot.xts(x)) still shows no chart and instead prints my xts object! I.e. it does exactly the same as print(x).
The script I use to run unit tests is:
#!/usr/bin/Rscript --slave library('RUnit') options(warn=2) #Turn warnings into errors #By naming the files runit.*.R, and naming the functions test*(), we can use # all the defaults to defineTestSuite(). #NOTE: they have a weird default random number generator, so changed here # to match the R defaults instead. test.suite=defineTestSuite('tests',dirs=file.path('tests'), rngKind = "Mersenne-Twister", rngNormalKind = "Inversion") test.result <- runTestSuite(test.suite) printTextProtocol(test.result)
The script below does two things:
plot to a device file, as you would in headless setting such as a webserver,
plot a screen device, I use x11() but you could use win().
There is no limitation imposed by Rscript. And this has nothing to do with xts as you could just as easily plot an xts object.
#!/usr/bin/Rscript set.seed(42) x <- cumsum(rnorm(100)) png("/tmp/darren.png") plot(x) dev.off() x11() plot(x) Sys.sleep(3) # could wait for key pressed or ...