Michael Street
Michael Street

Reputation: 645

Plot a 24 hour cycle monthly for multiple variables?

I have data that can be mimicked in the following manner:

set.seed(1234)

foo <- data.frame(month = rep(month.name, each = 24),
              hour = rep(seq(1:24), 12),
              value1 = rnorm(nrow(foo), 60, 1),
              value2 = rnorm(nrow(foo), 60, 1))

foo <- melt(foo, id = c('month', 'hour'))

I would like to create a plot for the entire year using ggplot that displays the 24 hour cycle of each variable per month.

Here's what I've tried so far:

t.plot <- ggplot(foo,
             aes(interaction(month,hour), value, group = interaction(variable,hour)))

t.plot <- t.plot + geom_line(aes(colour = variable))
print(t.plot)

I get this, which throws the data into misalignment. For such a small SD you see that the first 24 values should be nearer to 60, but they are all over the place. I don't understand what's causing this discrepancy.

https://www.dropbox.com/s/rv6uxhe7wk7q35w/foo.png

when I plot:

plot(interaction(foo$month,foo$hour)[1:24], foo$value[1:24])

I get the shape that I would expect however the xaxis is very strange and not what I was expecting.

Any help?

Upvotes: 1

Views: 704

Answers (1)

mnel
mnel

Reputation: 115435

The solution is to set your dates to be dates (not an interaction of a factor)

eg

library(lubridate)
library(reshape2)
Date <- as.Date(dmy('01-01-2000') + seq_len(24*365)*hours(1))
foo <- data.frame(Date = Date, 
  value1 = arima.sim(list(order = c(1,1,0), ar = 0.7), n = 24*365-1), 
   value2 = arima.sim(list(order = c(1,1,0), ar = 0.7), n = 24*365-1))
foo_melt <- melt(foo, id = 'Date')

# then you can use `scale_x_date` and `r` and ggplot2 will know they are dates
# load scales library to access date_format and date_breaks
library(scales) 
ggplot(foo_melt, aes(x=Date, y=value, colour = variable)) + 
 geom_line() +
 scale_x_date(breaks = date_breaks('month'), 
              labels = date_format('%b'), expand =c(0,0))

enter image description here

Edit 1 average day per month

you can use facet_wrap to facet by month

# using your created foo data set
levels(foo$month) <- sort(month.abb)
foo$month <- factor(foo$month, levels = month.abb)
ggplot(foo, aes(x = hour, y=value, colour = variable)) + 
 facet_wrap(~month) + geom_line() + 
 scale_x_continuous(expand = c(0,0)))

enter image description here

Upvotes: 4

Related Questions