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))
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))
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With