[英]Temporal density plot in R
我對一個現象的觀察結果進行了不規則的測量,每個觀察結果都帶有時間戳:
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日等)的標簽:
但是,重要的是,測量點本身在圖中是可見的,就像上面一樣。
#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
導致
現在,如果您想進一步調整x軸標簽(因為您希望每個單獨的日期都被標記,則可以使用scales
包。我們將使用scale_x_date
但這僅包含“ 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
這給出:
請注意,時間似乎已經四舍五入了。
希望這可以幫助您前進。
將您的值轉換為POSIXct,轉換該數字(即UNIX時間中的秒),然后應用內核密度函數。 如果z
是您的時間戳向量:
z2 <- as.POSIXct(z, "%Y-%m-%d %H:%M:%S", tz="GMT")
plot(density(as.numeric(z2)))
這樣,相對容易地添加帶有axis
的標記x axis
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.