如何将一周中每一天的平均每小时数据可视化为 R 中七天的 facet_wrap?

How to visualize average hourly data for each day in a week as a facet_wrap of seven days in R?

我有一个长数据框,由以下列组成:日期、小时、日、周、工作日、值

这里是:

df <- structure(list(Date = structure(c(1482087600, 1482084000, 1482080400, 
1482076800, 1482073200, 1482069600, 1482066000, 1482062400, 1482058800, 
1482055200), class = c("POSIXct", "POSIXt"), tzone = ""), hour = 23:14, 
    day = c(18L, 18L, 18L, 18L, 18L, 18L, 18L, 18L, 18L, 18L), 
    week = c(51, 51, 51, 51, 51, 51, 51, 51, 51, 51), weekdays = c("Sunday", 
    "Sunday", "Sunday", "Sunday", "Sunday", "Sunday", "Sunday", 
    "Monday", "Monday", "Monday"), Value= c(18L, 20L, 25L, 
    29L, 31L, 32L, 30L, 23L, 24L, 17L)), row.names = c(NA, 10L
), class = "data.frame")
df

我想通过对每天每个小时的“值”列中的数据进行平均来可视化七个工作日的 facet_wrap 小时数。例如,星期一的第 2 小时应包括每个星期一的 2 小时平均值,星期二的第 3 小时应包括每个星期二的第 3 小时的小时平均值,依此类推。

到目前为止,我的代码如下所示:

df%>%
  group_by(day) %>%
  group_by(hour)
  summarise(avg_hour = mean(Value)) %>%
  ggplot(aes(x=hour, y=Value, color = weekdays)) + 
  geom_line() + 
  ylab("Value") + 
  xlab("Hours")

但是,我不断收到此错误:

Don't know how to automatically pick scale for object of type function. Defaulting to continuous.
Error: Aesthetics must be valid data columns. Problematic aesthetic(s): x = hour. 
Did you mistype the name of a data column or forget to add after_stat()?

如果有人能帮我找到正确的情节,我将不胜感激。

你可以得到你使用后的情节:

df %>%
  group_by(day) %>%
  group_by(hour) %>%
  mutate(avg_hour = mean(Value)) %>%
  ungroup() %>%
  ggplot(aes(x=hour, y=avg_hour)) + 
  geom_line() + 
  ylab("Value") + 
  xlab("Hours") +
  facet_wrap(vars(weekdays))


您的代码存在一些问题:

  • 您的 group_by 缺少通往 summarise
  • 的管道
  • 您想绘制派生列 avg_hour 而不是 原始列 Value
  • summarise() 删除既不是分组列也不是由汇总生成的所有列,因此 weekdays 不可用。因此我用 mutate() %>% ungroup() 代替
  • 你错过了我添加的实际 facet_wrap()