How to make a timeseries boxplot in R

前端 未结 3 920
忘掉有多难
忘掉有多难 2020-12-03 06:08

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

3条回答
  •  没有蜡笔的小新
    2020-12-03 06:40

    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.

提交回复
热议问题