首页 > 解决方案 > Rscript 无法从命令行绘制 xts

问题描述

我有一个Rscript对我有用的东西,其中之一是绘制股票价格数据(它可以是每日、每小时或滴答数据)。我能够从终端发出命令 plot matrix,但绘图xts不起作用。

下面我使用docopt包来实现一个过于简化的R命令行界面,足以证明所描述的问题。我相信这个问题更多,plot因此xts更改命令行界面实现应该是安全的(但您必须保持测试功能完好无损)。

当我test.matrix()从 CLI 运行时,打开了一个 png 文件,显示了我期望的情节。当我test.xts()从 CLI 运行时,弹出错误提示没有名为“test2.png”的文件;对于xts对象,该文件甚至没有开始。

为什么在这种情况下绘图xts不起作用?是否有xts从 CLI 绘图的解决方法?

我正在运行基于 Debian 10 的 Linux 系统。

# code in test.R

library(dplyr)
library(xts)

test.matrix <- function(){
  data(sample_matrix)
  png("test.png")
  plot(x = sample_matrix,
       main = paste("Test", "xts", sep=" "))
  dev.off()
  browseURL("test.png")
}
test.xts <- function(){
  data(sample_matrix)
  png("test2.png")
  sample.df <- sample_matrix %>% as.data.frame()
  test.data <- sample.df$Open
  test.date <- as.Date(rownames(sample.df))
  test <- xts(test.data, order.by=test.date)
  plot(x = test,
       main = paste("Test", "xts", sep=" "))
  dev.off()
  browseURL("test2.png")
}

# code in Rscript rf.R
# rf.R test
#!/usr/bin/Rscript --vanilla

# for demo purpose, the actual paths to r files are omitted.
# They are just the usual absolute paths to files under project directory.
suppressMessages(source('test.R'))

readr::read_file('rf_doc') -> doc
args <- docopt(doc, "test", version="1.0\n") 

if (args$test){
  test.xts()
 #test.matrix()
}

# rf_doc, a plain txt file (in Linux it has no file extension).
# the file dictates how the rf command is going to work.
# the pattern is used by `docopt` package.

Usage:
rf test
rf --help

Options:
--help  show this help page.

标签: plotcommand-line-interfacextszoo

解决方案


推荐阅读