简体   繁体   中英

Boxplot by Date in R

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.

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM