简体   繁体   中英

How to make a timeseries boxplot in R

I'm trying to make a time series boxplot using ggplot2 .

I have montly values for many individuals.

I need to make a timeseries boxplot by month with my data.

I think that my problem is how to create a factor (month) with my data.

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

在此输入图像描述

另一种方法是不必更改日期格式并进行任何排序等,只需将日期添加为分组因子,如下所示:

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

Updated: Based on OP's clarification that multiple years have to be handled separately.

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

Which produces: 在此输入图像描述

Hope this helps you move forward.

I create a function to create the plot you need.

the function is:

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

Fox example:

 ts_plot_season(AirPassengers)

时间序列的Boxplot

I hope this help. I know this question is old, but i couldn't find some god answer on the web. So i think this will help to someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM