2011-06-22 71 views
0

我是初學者,嘗試使用R來製作圖表。請幫幫我。我有多列數據(時間序列)。每列包含因素(請參閱下面的一列示例數據)。我想製作時間序列的不變高度(比如1單位)條形圖,並希望用X軸上的DATE以不同顏色表示「A」和「B」。任何提示? 提前感謝您!時間序列中因素的高度不變的條形圖

DATE      GROUP 
2011.06.18 00:00:00   R 
2011.06.18 06:00:00   L 
2011.06.18 12:00:00   R 
2011.06.18 18:00:00   R 
2011.06.19 00:00:00   L 
2011.06.19 06:00:00   L 
2011.06.19 12:00:00   R 
2011.06.19 18:00:00   L 
2011.06.20 00:00:00   L 
2011.06.20 06:00:00   L 
2011.06.20 12:00:00   R 
2011.06.20 18:00:00   L 
2011.06.21 00:00:00   R 
2011.06.21 06:00:00   L 
+0

什麼是A和B?目前,你有一個因子L和R.你的意思是你有幾個像GROUP這樣的列,每個列都是一個L或一個R.你想要計算每個時間點的Ls和Rs,然後顯示爲堆疊條形圖? –

回答

1

假設你的數據在dat,但有一個額外的列:

dat <- structure(list(DATE = structure(list(sec = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0), min = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L), hour = c(0L, 6L, 12L, 18L, 0L, 6L, 
12L, 18L, 0L, 6L, 12L, 18L, 0L, 6L), mday = c(18L, 18L, 18L, 
18L, 19L, 19L, 19L, 19L, 20L, 20L, 20L, 20L, 21L, 21L), mon = c(5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), year = c(111L, 
111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 
111L, 111L), wday = c(6L, 6L, 6L, 6L, 0L, 0L, 0L, 0L, 1L, 1L, 
1L, 1L, 2L, 2L), yday = c(168L, 168L, 168L, 168L, 169L, 169L, 
169L, 169L, 170L, 170L, 170L, 170L, 171L, 171L), isdst = c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("sec", 
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst" 
), class = c("POSIXlt", "POSIXt")), GROUP = structure(c(2L, 1L, 
2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L), .Label = c("L", 
"R"), class = "factor"), GROUP2 = structure(c(1L, 2L, 2L, 1L, 
2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L), .Label = c("L", "R"), class = "factor")), .Names = c("DATE", 
"GROUP", "GROUP2"), row.names = c(NA, -14L), class = "data.frame") 

那麼我想這個你想要做什麼。第一計數==到類別中的一個元素

counts <- apply(dat[, 2:3], 1, function(x) sum(x == "R")) 

然後計算其他計數和結合到基質:

countmat <- t(cbind(L = (NCOL(dat) - 1) - counts, R = counts)) 

然後我們繪製使用barplot()

op <- par(mar = c(9,4,4,2) + 0.1, las = 2) 
mids <- barplot(countmat, ylim = c(0,2.5), 
       legend.text = c("L","R"), 
       args.legend = list(x = "top", bty = "n")) 
axis(side = 1, at = mids, labels = as.character(dat$DATE)) 
par(op) 

產生:

barplot of time series

請參閱各個函數的幫助頁面以解釋參數。

編輯:如果你只是想爲一個單獨的列做到這一點,那麼這是不是最有趣的圖形,但是......

count2 <- with(dat, GROUP == "R") 
countmat2 <- t(cbind(R = count2, L = !count2)) 

op <- par(mar = c(9,4,4,2) + 0.1, las = 2) 
mids <- barplot(countmat2, ylim = c(0, 1.5), 
       legend.text = c("R","L"), 
       args.legend = list(x = "top", bty = "n")) 
axis(side = 1, at = mids, labels = as.character(dat$DATE)) 
par(op) 

這使這個數字:

enter image description here