How to make a timeseries boxplot in R

前端 未结 3 889
忘掉有多难
忘掉有多难 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.

    0 讨论(0)
  • 2020-12-03 06:40

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

    0 讨论(0)
  • 2020-12-03 06:42

    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.

    0 讨论(0)
提交回复
热议问题