Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a timeseries boxplot in R

Tags:

r

ggplot2

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

enter image description here

like image 751
fandreacci Avatar asked Mar 13 '14 19:03

fandreacci


3 Answers

Another way to do this without having to change to date format and do any sorting etc. is to simply add the date as a grouping factor like so:

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

like image 131
dom_oh Avatar answered Nov 09 '22 22:11

dom_oh


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: enter image description here

Hope this helps you move forward.

like image 36
Ram Narasimhan Avatar answered Nov 09 '22 21:11

Ram Narasimhan


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 for time series

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.

like image 3
Victor Espinoza Avatar answered Nov 09 '22 22:11

Victor Espinoza