如何在R中制作时间序列箱线图

9

我正在尝试使用 ggplot2 生成一个时间序列箱线图。

我有许多个体的月度值。

我需要根据月份制作我的数据的时间序列箱线图。

我认为我的问题是如何使用我的数据创建一个因子(月份)。

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

enter image description here


据我所知,箱线图使用分类数据作为x轴。实际上,这将把日期转换为标签而不是日期,剥夺了那里的信息。我不确定是否有正确的方法在x轴上绘制时间,以便保留时间间隔(节奏?)。 - Andy Clifton
制作类似于这样的东西:![http://i.imgur.com/bM6Lyje.png] - fandreacci
3个回答

14

在不必更改日期格式、排序等的情况下,另一种方法是将日期作为分组因素添加,例如:

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


5

更新:根据提问者的澄清,需要单独处理多年份。

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))

这会产生以下结果: 在此输入图片描述

希望这能帮助您前进。


1
谢谢Ram,它起作用了。 然而,它将所有不同年份的月份分组在一起。 我的数据范围从2010年到2011年,所以我需要2个“jan,feb,mar…”。 有什么想法吗? - fandreacci
我已更新我的答案,以便每个“年-月”都单独绘制而不是分组。 - Ram Narasimhan

3

我创建了一个函数以创建您所需的图表。

该函数如下:

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)

时间序列的箱线图

希望这能有所帮助。我知道这个问题已经很老了,但是我在网上找不到什么好的答案。因此我认为这会对某些人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接