创建周期图

时间:2017-11-11 14:37:27

标签: r ggplot2 tidyverse

我希望在几个月内创建一个小时的循环图。我希望它看起来像下面的情节。我的目标是用水平线指示每个月的平均温度,然后在每个月内用图表显示该月典型日的温度波动。我试图使用monthplot(),但似乎没有工作:

enter image description here

library(nycflights13)

tempdata <- weather %>% group_by(hour) 

monthplot(tempdata, labels = NULL, ylab = "temp")

它一直说argument is not numeric or logical: returning NA,但我不确定代码出错的地方。

2 个答案:

答案 0 :(得分:4)

希望这个ggplot2解决方案能够正常运行:

library(nycflights13)
library(ggplot2)
library(dplyr)

# Prepare data
tempdata <- weather %>% 
    group_by(month, day) %>%
    summarise(temp = mean(temp, na.rm = TRUE))
meanMonth <- tempdata %>%
    group_by(month) %>%
    summarise(temp = mean(temp, na.rm = TRUE))

# Plot using ggplot2
ggplot(tempdata, aes(day, temp)) +
    geom_hline(data = meanMonth, aes(yintercept = temp)) +
    geom_line() +
    facet_grid(~ month, switch = "x") +
    labs(x = "Month",
         y = "Temperature") +
    theme_classic() +
    theme(axis.ticks.x = element_blank(),
          axis.text.x = element_blank(),
          axis.line.x = element_blank())

enter image description here

答案 1 :(得分:2)

temp缺少值会导致错误。您还需要设置timesphase参数。

library(nycflights13)

# Find mean value : this automatically removes the observation with missing data that was causing an error
tempdata <- aggregate(temp ~ month + day, data=weather, mean) 

with(tempdata, monthplot(temp, times=day , phase=month, ylab = "temp"))

enter image description here