Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boxplot by Date in R

Tags:

r

zoo

boxplot

xts

I have data collected daily over time. I would like to plot the data as a boxplot that summarizes DAILY data. Most of the examples that I have seen have data collected on a daily or monthly basis, and make boxplots out of those.

As an example:

    library(xts)
 dates=c(rep("2011-02-11",8),rep("2011-02-13",8),rep("2011-02-19",8))
measure=rnorm(length(dates))
example <- as.xts( measure,order.by = as.Date( dates ))
boxplot(coredata(example), order.by=index(example),.CLASS = "xts")

I end up with no separation by date.

I cannot figure this out. I think it might have something to do with how R handles X values, I heard that it turns them into factors. Any help would be very appreciated.

like image 365
Robin Choudhury Avatar asked Mar 27 '26 06:03

Robin Choudhury


1 Answers

This is a solution using data.frame instead of as.xts:

example <- data.frame(dates=as.Date(dates),measure=measure)
boxplot(example$measure ~ example$dates)

enter image description here

Update

A way to create spaces for missing dates is to make a new dataset that contains NA's for all missing dates, and then allow for NA's in the boxplot.

Original example

dates=c(rep("2011-02-11",8),rep("2011-02-13",8),rep("2011-02-19",8))
measure=rnorm(length(dates))
example <- data.frame(dates=as.Date(dates),measure=measure)

Create a template data.frame, with start date and en date

n=20
template<-data.frame(dates = seq(as.Date(c("2011-02-11")), by = 'day', length = n)) 

Merge the template and example sothat the missing dates have value NA for your variable "measure", and finally boxplot.

df<-merge(template, example, all.x=TRUE, by="dates")

boxplot(df$measure ~ addNA(df$dates))

enter image description here

like image 177
Ruthger Righart Avatar answered Mar 29 '26 01:03

Ruthger Righart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!