每月为多个变量绘制24小时循环?

时间:2012-10-04 04:23:41

标签: r ggplot2

我的数据可以通过以下方式模仿:

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

我想使用ggplot创建一整年的情节,显示每月每个变量的24小时循环。

这是我到目前为止所尝试的内容:

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)

我得到了这个,这会导致数据不对齐。对于如此小的SD,您会看到前24个值应该接近60,但是它们遍布整个地方。我不明白是什么导致了这种差异。

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

当我画情节时:

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

我得到了我期望的形状,但是xaxis非常奇怪,而不是我所期待的。

任何帮助?

1 个答案:

答案 0 :(得分:4)

解决方案是将日期设置为日期(不是因素的交互)

例如

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

每月平均编辑1次

你可以按月使用facet_wrap进行分面

# 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

相关问题