2016-02-28 154 views
1

我是R新手。 我在这个链接dropbox中有一套每日数据。我的代码是:在R中绘制时间系列

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

这是结果:

[Graph][2].

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

我将不胜感激的如何获得DATE变量在图表。

非常感谢。

+0

是的,我可以用Excel修改它。 –

回答

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) 

Left is with zoo. Right is with xts

+0

非常感谢。 –

0

尝试使用

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

这是R消息 datatest $ DATE = as.POSIXct(datatest $ DATE) as.POSIXlt.character(as.character(x),...)中的错误: 字符串不是标准的明确格式' –

+0

如果我在文件csv中更改为短日期格式,那么我如何将DATE变量添加到时间序列图中? –

0
dataset$DATE <- as.Date(dataset$DATE, format = "%A, %B %d, %Y") 
  • %A - 长平日
  • %B - 完整的月份名称
  • %d - 两位数日期
  • %Y - 四位数年份