A subset of boxes by date, x-axis by month

I have data for a year covering two calendar years. I want to build boxes for these subsets of monthly data.

The charts will always be ordered alphabetically (if I use the names of the months) or numerically (if I use the numbers of the month). My goal doesn't suit me.

In the example below, I want the months on the x-axis to start in June (2013) and end in May (2014).

date <- seq.Date(as.Date("2013-06-01"), as.Date("2014-05-31"), "days")

set.seed(100)
x <- as.integer(abs(rnorm(365))*1000)

df <- data.frame(date, x)

boxplot(df$x ~ months(df$date), outline = FALSE)

Perhaps I could generate a vector of months in the order I need (for example, months <- months(seq.Date(as.Date("2013-06-01"), as.Date("2014-05-31"), "month")))

Is there a more elegant way to do this? What am I missing?

+4
source share
3 answers

You are looking for something like this:

boxplot(df$x ~ reorder(format(df$date,'%b %y'),df$date), outline = FALSE) 

reorder . , , .

enter image description here

:

( ? ):

boxplot(df$x ~ reorder(format(df$date,'%B'),df$date), outline = FALSE)

enter image description here

EDIT2 ggplot2:

, ggplot2:)

library(ggplot2)

ggplot(df) +
  geom_boxplot(aes(y=x,
                   x=reorder(format(df$date,'%B'),df$date),
                   fill=format(df$date,'%Y'))) +
  xlab('Month') + guides(fill=guide_legend(title="Year")) +
  theme_bw()

enter image description here

+4

, . , , , :

date <- seq.Date(as.Date("2013-06-01"), as.Date("2014-05-31"), "days")

set.seed(100)
x <- as.integer(abs(rnorm(365))*1000)

months <- month.name
boxplot(x~as.POSIXlt(date)$mon,names=months, outline = FALSE)
+1

The answer is found here - use the coefficient, not the date:

set.seed(100)
x <- as.integer(abs(rnorm(365))*1000)

df <- data.frame(date, x)

# create an ordered factor
m <- months(seq.Date(as.Date("2013-06-01"), as.Date("2014-05-31"), "month"))
df$months <- factor(months(df$date), levels = m)

# plot x axis as ordered
boxplot(df$x ~ df$months, outline = FALSE)

plot ordered

0
source

All Articles