2013-06-12 29 views
2

我對R很新,所以請溫和。削減數據和訪問組以繪製百分比線

我有一個包含時間戳和一些數據的數據集。 現在我想畫一張圖,其中:

  • 數據按照例如60分鐘間隔和
  • 繪製了一些百分比線。

我想有一個圖表,時間爲x軸,間隙爲y軸。 我想象像箱圖,但爲了更好地概述 - 因爲我有一個長的測量 - 而不是箱子,我想有一個連接

  • 均值線,
  • 3百分位,
  • 97個百分位數和
  • 100百分

下面是一個例子的數據:

> head(B, 10) 
         times  gaps 
1 2013-06-10 15:40:02.654168 1.426180 
2 2013-06-10 15:40:18.936882 2.246462 
3 2013-06-10 15:40:35.215668 3.227132 
4 2013-06-10 15:40:48.328785 1.331284 
5 2013-06-10 15:40:53.809485 1.294128 
6 2013-06-10 15:41:04.027745 2.292671 
7 2013-06-10 15:41:25.876519 1.293501 
8 2013-06-10 15:41:42.929280 1.342166 
9 2013-06-10 15:42:11.700626 3.203901 
10 2013-06-10 15:42:23.059550 1.304467 

我可以用切分數據:

C <- table(cut(B, breaks="hour")) 

C <- data.frame(cut(B, breaks="hour")) 

但我怎麼能繪製圖形的形式呢?我不知道如何獲得團體的差距值。否則,我可能

quantile(C$gaps, c(.03, .5, .97, 1)) 

預先感謝任何幫助 拉蒙

回答

2

固體問題。我拉着我的頭髮,直到我發現this,其中描述了plyr的一個有趣的「特徵」。所以這個解決方案利用了ggplot,plyr,reshape2-希望能成爲R的一個很好的介紹。如果你需要通過幾天添加剪輯,你還可以通過在ddply()中添加一個變量來實現。

library(plyr) 
library(reshape2) 
library(ggplot2) 
Hs <- read.table(
    header=TRUE, text=' 
dates times  gaps 
1 2013-06-10 15:40:02.654168 1.426180 
2 2013-06-10 15:40:18.936882 2.246462 
3 2013-06-10 15:40:35.215668 3.227132 
4 2013-06-10 15:40:48.328785 1.331284 
5 2013-06-10 15:40:53.809485 1.294128 
6 2013-06-10 15:41:04.027745 2.292671 
7 2013-06-10 16:41:25.876519 1.293501 
8 2013-06-10 16:41:42.929280 1.342166 
9 2013-06-10 16:42:11.700626 3.203901 
10 2013-06-10 16:42:23.059550 1.304467') 
Hs$dates <- paste(Hs$date, Hs$times, sep = " ") 
Hs$dates <- strptime(Hs$date, "%Y-%m-%d %H:%M:%S") 
class(Hs$dates) # "POSIXlt" "POSIXt" 
Hs$h1 <- Hs$dates$hour 
Hs$dates <- as.POSIXct(strptime(Hs$date, "%Y-%m-%d %H:%M:%S")) 
class(Hs$dates) # "POSIXct" "POSIXt" 
library(ggplot2) 
ggplot(Hs, aes(factor(h1), gaps)) + 
    geom_boxplot(fill="white", colour="darkgreen") # easy way! Traditional boxplot. 
ggplot(Hs, aes(factor(h1), gaps)) + geom_boxplot() + 
     stat_boxplot(coef = 1.7, fill="white", colour="darkgreen") 

我不知道,如果加入「COEF = 1.7」適用於你 - 如果沒有進一步繼續通過彙總表創造價值

cuts <- c(.03, .5, .97, 1) 
x <- ddply(Hs, .(h1), function (x) 
{summarise(x, y = quantile(x$gaps, cuts))}) 
x$cuts <- cuts 
x <- dcast(x, h1 ~ cuts, value.var = "y") 
x.melt <- melt(x, id.vars = "h1") 

這裏有你所要求的行加另一個箱子情節只是爲了好玩。

ggplot(x.melt, aes(x = h1, y = value, color = variable)) + geom_point(size = 5) + 
    geom_line() + scale_colour_brewer(palette="RdYlBu") + xlab("hours") 
ggplot(x, aes(factor(h1), ymin = 0, lower = `0.03`, middle = `0.5`, 
        upper = `0.97`, ymax = `1`)) + 
     geom_boxplot(stat = "identity", fill="white", colour="darkgreen") 

geom_line

custom boxplot

希望這有助於。

+0

精彩回答! – Powderking

+0

還了解了POSIXlt,class(),ddply(),summarize(),我的問題也得到了解答:-)非常感謝! – Powderking