【问题标题】:Plotting time series in R在 R 中绘制时间序列
【发布时间】:2016-02-28 17:27:12
【问题描述】:

我是 R 新手。 我在此链接dropbox 中有一组每日数据。我的代码是:

#plotting CLOSE
plot.ts(datatest$CLOSE,ylab="Close")

这是结果:

问题是xlab,我想显示DATE 变量,但似乎显示CLOSE 变量的顺序。我还尝试了其他命令,如 ggplotxyplot 等,但它们需要转换为 data.frame,这对我来说太难了。

我将不胜感激有关如何在图表中获取 DATE 变量的指导。

非常感谢。

【问题讨论】:

  • 可以,我可以用 Excel 修改。

标签: r plot time-series


【解决方案1】:

这样就可以了:

# load data:
theData = read.csv2(file = "sample.csv",header = TRUE,
                    stringsAsFactors = FALSE,sep = ",",
                    colClasses = c("character",rep("numeric",5)),dec=".")

# We want to plot a custom x-axis, so stop the default
# x-axis being drawn usign xaxt="n":
plot(theData$CLOSE,type="l",xaxt="n")

# Lets say you want to put a date label in 8 different locations:
locations = floor(seq(from=1,to=nrow(theData),by=nrow(theData)/8))

# Now draw the x-axis on your plot like this:
axis(side = 1, at = locations, labels=theData$DATE[locations],las=2)

在上面,side=1 表示在底部绘制轴。 at=locations 表示我们希望在我们之前创建的位置向量中给定的位置显示刻度标签。 labels=theData$DATE[locations] 提供了我们想要放置在我们放置标签的位置的标签。 las=2 表示您要旋转刻度标签。也可以尝试 las=1 进行不同的轮换。

但是,这些日期有点长,因此您可能希望创建更小的日期,如下所示:

# Convert your long dates to smaller dates like YYYY-MM-DD, and stick
# the results to the end of your data frame.
theData = cbind(theData,
                "FormattedDate"=as.Date(theData$DATE,"%A, %B %e, %Y"))

# Replot and use your smaller dates. (ces.axis=0.8 makes
# the font smaller)
plot(theData$CLOSE,type="l",xaxt="n")
axis(side = 1, at = locations,
     labels=theData$FormattedDate[locations],las=1,cex.axis=0.8)

最后,您还可以使用一些不错的时间序列包来轻松创建更好的图:

install.packages("xts")
library(xts)
xtsData = xts(theData[,"OPEN"],order.by = theData[,"FormattedDate"])
plot.zoo(xtsData)
# or
plot.xts(xtsData)

【讨论】:

    【解决方案2】:

    尝试使用

    dataset$DATE<-.as.POSIXct(dataset$DATE)
    

    【讨论】:

    • 这是R消息datatest$DATE=as.POSIXct(datatest$DATE) Error in as.POSIXlt.character(as.character(x), ...) : character string is not in a standard unambiguous format
    • 如果我在文件 csv 中更改为短日期格式,那么如何将 DATE 变量添加到时间序列图中?
    【解决方案3】:
       dataset$DATE <- as.Date(dataset$DATE, format = "%A, %B %d, %Y")
    
    • %A - 漫长的工作日
    • %B - 完整的月份名称
    • %d - 两位数日期
    • %Y - 四位数年份

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      相关资源
      最近更新 更多