Reputation: 314
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.
Upvotes: 3
Views: 4230
Reputation: 4921
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)
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))
Upvotes: 2