使用r绘制时间序列,转换日期

时间:2014-08-19 07:52:20

标签: r

 date.value
1     1/1/2012;5.1249091
2     2/1/2012;4.7141472
3     3/1/2012;2.0218712
4     4/1/2012;1.8655652
5     5/1/2012;2.3347499
6     6/1/2012;3.2804476
7     7/1/2012;4.0427648
8     8/1/2012;4.2743314
9     9/1/2012;2.1511432
10   10/1/2012;2.6610649
11   11/1/2012;2.2907005
12   12/1/2012;2.4893108
13   13/1/2012;2.9927042

如何为此绘制时间序列图,x轴显示月份/年份,如"01/2012,02/2012",依此类推。

3 个答案:

答案 0 :(得分:1)

如果您的数据是dat

library(reshape2)
dat <- colsplit(dat$date.value, ";", c("date", "value"))
dat$date <- as.Date(strptime(dat$date, "%d/%m/%Y"))
library(ggplot2)
library(scales)
ggplot(dat, aes(date, value, group = 1)) + geom_line() + 
scale_x_date(labels = date_format("%d/%m/%Y"))

enter image description here

答案 1 :(得分:1)

你也可以这样做:

 library(xts)
 xt1 <- xts(dat[,-1], order.by=dat[,1])
 plot(xt1, major.format="%d/%Y", xlab="date", ylab="value", main="xts plot")

要显示months/years,请更改major.format="%m/%Y"

数据

  dat <-  structure(list(date = structure(c(15340, 15341, 15342, 15343, 
  15344, 15345, 15346, 15347, 15348, 15349, 15350, 15351, 15352
  ), class = "Date"), value = c(5.1249091, 4.7141472, 2.0218712, 
  1.8655652, 2.3347499, 3.2804476, 4.0427648, 4.2743314, 2.1511432, 
  2.6610649, 2.2907005, 2.4893108, 2.9927042)), .Names = c("date", 
  "value"), row.names = c(NA, -13L), class = "data.frame")

enter image description here

答案 2 :(得分:0)

您也可以在包中使用separate()

separate(dat, date.value, c("date", "value"), sep=";")