2010-08-16 90 views
5

我有時間序列數據(我已經在這裏張貼作爲一個data.frame):barplot與ggplot月總計?

x <- structure(list(date = structure(c(1264572000, 1266202800, 1277362800, 
1277456400, 1277859600, 1278032400, 1260370800, 1260892800, 1262624400, 
1262707200), class = c("POSIXt", "POSIXct"), tzone = ""), data = c(-0.00183760994446658, 
0.00089738603087497, 0.000423513598318936, 0, -0.00216496690393131, 
-0.00434836817931339, -0.0224199153445617, 0.000583823085470003, 
0.000353088613905206, 0.000470295331234771)), .Names = c("date", 
"data"), row.names = c("1", "2", "3", 
"4", "5", "6", "7", "8", "9", "10" 
), class = "data.frame") 

什麼是繪製本作中ggplot柱狀圖,將顯示每月總價值的最佳方式(月份名稱爲文本)?

我可以通過添加個月的實地手動執行此操作:

x$month <- format(x$date, format="%B") 
ddply(x, .(month), function(x) sum(x[, "data"])) 

然後獨立繪製這一點,但使用這種方法(?假設我需要建立一個有序的因素)幾個月未排序正確;我也假設ggplot有一個「更容易」的方法。

回答

12

我絕不是時間序列數據的專家,但是這個代碼爲我工作:

#The binning by month, saving as a date 
x$month <- as.Date(cut(x$date, breaks = "month")) 

#Plotting 
p <- ggplot(x, aes(month, data))+ 
    stat_summary(fun.y = sum, geom = "bar") 

#My suggestions for display 
minmax <- max(abs(x$data)) 

p + geom_hline(y = 0)+ 
    scale_x_date(minor = "month")+ 
    ylim(-minmax, minmax) 
    # or more ggplot2 accurately 
    #+coord_cartesian(ylim = c(-minmax, minmax)) 

隨着我的建議,你最終突出爲零線,與y軸對稱大約爲0.我將x軸小網格線更改爲「月」,因爲每個月的酒吧在每個方向上延長了幾周,這對於數據如何聚合沒有實際意義。

編輯: 當然,這些代碼大部分只是創建每月的總和。如果您的日期數據採用日期格式,則日期刻度會自動用於軸。要更改主X休息和它們的格式,你scale_x_date()

p + scale_x_date(major = "month", format = "%b") 
#or 
p + scale_x_date(major = "month", format = "%B %Y") 

做到見?strftime關於什麼格式字符串的意思的細節。