我正在試圖使用ggplot2
來創建時間序列箱型圖。如何在R中創建時間序列箱圖
我對許多個人都有着單調的價值。
我需要按月使用我的數據製作時間序列箱線圖。
我認爲我的問題是如何用我的數據創建一個因子(月)。
p <- ggplot(mydata, aes(factor(date), measure))
我正在試圖使用ggplot2
來創建時間序列箱型圖。如何在R中創建時間序列箱圖
我對許多個人都有着單調的價值。
我需要按月使用我的數據製作時間序列箱線圖。
我認爲我的問題是如何用我的數據創建一個因子(月)。
p <- ggplot(mydata, aes(factor(date), measure))
更新時間:基於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))
主要生產:
希望這有助於你前進。
謝謝拉姆,它的工作。 但是,它是在同一個月中將所有不同年份分組的。 我的數據範圍從2010年到2011年,所以我需要2「1月,2月,3月...」。 任何想法? – fandreacci
我已更新我的答案,以便每個「年 - 月」分別繪製而不分組。 –
另一種方式來做到這一點,而無需改變日期格式,做任何排序等是簡單地添加日期作爲像這樣一個聚合因子:
ggplot(mydata) + geom_boxplot(aes(x = date, y = measure, group = date))
據我所知,boxplots使用分類數據作爲x軸。實際上,這會將日期變成標籤而不是日期,從而將信息剝離。我不確定是否有辦法在x軸上正確繪製時間,以便保留時間的間距(節奏?)。 –
爲了這樣: ![http://i.imgur.com/bM6Lyje.png] – fandreacci