R中的时间密度图

时间:2013-05-24 08:07:40

标签: r plot time-series kernel-density

我不定期地测量了每个时间戳现象的观察结果:

2013-01-03 00:04:23
2013-01-03 00:02:04
2013-01-02 23:45:16
2013-01-02 23:35:16
2013-01-02 23:31:56
2013-01-02 23:31:30
2013-01-02 23:29:18
2013-01-02 23:28:43
...

现在我想在x轴上绘制这些点并对它们应用核密度函数,因此我可以使用各种带宽直观地探索时间密度。虽然下面的例子不使用x轴标记,但事实证明应该是这样的。我希望有标签,例如特定日期(1月1日,1月5日等):

kernel density plot

然而,重要的是,测量点本身在图中可见,如上所述。

2 个答案:

答案 0 :(得分:2)

#dput
df <- structure(list(V1 = structure(c(2L, 2L, 1L, 3L, 1L, 4L, 5L, 4L), .Label = c("2013-01-02", "2013-01-03", "2013-01-04", "2013-01-05", "2013-01-11"), class = "factor"), V2 = structure(c(1L, 3L, 8L,  4L, 7L, 6L, 5L, 2L), .Label = c(" 04:04:23", " 06:28:43", " 10:02:04", " 11:35:16", " 14:29:18", " 17:31:30", " 23:31:56", " 23:45:16"), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, -8L))

使用ggplot,因为它可以对您的情节进行细粒度控制。使用不同的层进行测量和密度本身。

df$tcol<- as.POSIXct(paste(df$dte, df$timestmp), format= "%Y-%m-%d %H:%M:%S")
library(ggplot2)
measurements <- geom_point(aes(x=tcol, y=0), shape=15, color='blue', size=5)
kde <- geom_density(aes(x=tcol), bw="nrd0")
ggplot(df) + measurements +  kde

导致 enter image description here

现在,如果您想进一步调整x轴标签(因为您希望标记每个单独的日期,您可以使用scales包。 我们将使用scale_x_date但只接受'日期'

library(scales)
df$tcol <- as.Date(df$tcol, format= "%Y-%m-%d %H:%M:%S")
xlabel <- scale_x_date(labels=date_format("%m-%d"), breaks="1 day")
ggplot(df) + xlabel + measurements +  kde

这给出了: enter image description here

请注意,时间似乎已经过去了。

希望这有助于您前进。

答案 1 :(得分:0)

将您的值转换为POSIXct,转换该数字(即UNIX时间内的秒数),然后应用您的内核密度函数。如果z是您的时间戳矢量:

z2 <- as.POSIXct(z, "%Y-%m-%d %H:%M:%S", tz="GMT")
plot(density(as.numeric(z2)))

然后用axis添加标记的x轴相对容易。