2014-03-13 41 views
6

我正在試圖使用ggplot2來創建時間序列箱型圖。如何在R中創建時間序列箱圖

我對許多個人都有着單調的價值。

我需要按月使用我的數據製作時間序列箱線圖。

我認爲我的問題是如何用我的數據創建一個因子(月)。

p <- ggplot(mydata, aes(factor(date), measure)) 

enter image description here

+0

據我所知,boxplots使用分類數據作爲x軸。實際上,這會將日期變成標籤而不是日期,從而將信息剝離。我不確定是否有辦法在x軸上正確繪製時間,以便保留時間的間距(節奏?)。 –

+0

爲了這樣: ![http://i.imgur.com/bM6Lyje.png] – fandreacci

回答

1

更新時間:基於OP的澄清多年必須被另案處理。

library(ggplot2) 

#generate dummy data 
date_range <- as.Date("2010/06/01") + 0:400 
measure <- runif(401) 
mydata <- data.frame(date_range, measure) 

# create new columns for the months and years, and 
# and a year_month column for x-axis labels 
mydata$month <- format(date_range, format="%b") 
mydata$year <- as.POSIXlt(date_range)$year + 1900 
mydata$year_month <- paste(mydata$year, mydata$month) 
mydata$sort_order <- mydata$year *100 + as.POSIXlt(date_range)$mon 

#plot it 
ggplot(mydata) + geom_boxplot(aes(x=reorder(year_month, sort_order), y=measure)) 

主要生產: enter image description here

希望這有助於你前進。

+0

謝謝拉姆,它的工作。 但是,它是在同一個月中將所有不同年份分組的。 我的數據範圍從2010年到2011年,所以我需要2「1月,2月,3月...」。 任何想法? – fandreacci

+0

我已更新我的答案,以便每個「年 - 月」分別繪製而不分組。 –

8

另一種方式來做到這一點,而無需改變日期格式,做任何排序等是簡單地添加日期作爲像這樣一個聚合因子:

ggplot(mydata) + geom_boxplot(aes(x = date, y = measure, group = date))

0

我創建了一個函數來創建你需要的情節。

的功能是:

ts_plot_season <- function(x = x) { 
season <- cycle(x) 
season.factor <- factor(season) 
ggplot() + 
    geom_boxplot(mapping = aes(x = season.factor, 
          y = x)) + 
    labs(x = "Periodo", y = "Serie") 
} 

福克斯例如:

ts_plot_season(AirPassengers) 

Boxplot for time series

我希望這幫助。我知道這個問題很老,但我在網上找不到一些神的答案。所以我認爲這對別人有幫助。