Home > Blockchain >  Create a boxplot per year out of a ts object in R
Create a boxplot per year out of a ts object in R

Time:08-10

I have a ts object: 240 monthly observations stating from January 2000:

data <- runif(240)

data_ts <- ts(data,
              start = c(2000, 1),
              frequency = 12)

And I want to create a boxplot per year out of my data_ts.

I know how to create a boxplot per month:

boxplot(data_ts ~ cycle(data_ts))

But I don't know how to create a boxplot per year, that is, a boxplot of the observations of each year (a boxplot of year 2000, a boxplot of 2001, and so on).

Any idea?

Thanks!

CodePudding user response:

I use the window() function to subset the years, and a for() loop to iterate each year and create a boxplot(). The title() function adds the title to the plot, and png() and dev.off() work together to save the image to disk:

getwd() # print location files will be saved too.
for (i in 2010:2012) { # small loop for testing)
  png(file=paste("boxplot_",i,".png",sep=""))  # create a png
  boxplot(window(x=data_ts, start=c(i, 1), end=c(i, 12))) # boxplot, of yearly data.
  title(i) # add the year as a title to the plot
  dev.off() # save the png
}

CodePudding user response:

Maybe this also helps:

data <- runif(240)
data_ts <- ts(data,
              start = c(2000, 1),
              frequency = 12)

frame<-data.frame(values=as.matrix(data_ts), date=lubridate::year(zoo::as.Date(data_ts)))

library(ggplot2)
ggplot(frame,aes(y=values,x=date,group=date)) 
  geom_boxplot()

It is not the most elegant solution though as it uses both the zoo and lubridate packages to convert the date into a year that ggplot understands.

CodePudding user response:

The year is given as shown:

year <- as.integer(time(data_ts))
boxplot(data_ts ~ year)

screenshot

  • Related