ggplot如何在R中每个月获得单独的图

时间:2016-10-18 11:24:15

标签: r ggplot2

我希望每个月都有一个单独的情节(每个月总计12个情节)。我正在使用nycflights13数据集。

by_tailnum <- group_by(flights, tailnum)
delay <- summarise(by_tailnum,
                   count = n(),
                   dist = mean(distance, na.rm = TRUE),
                   delay = mean(arr_delay, na.rm = TRUE))
delay <- filter(delay, count > 20, dist < 2000)




ggplot(delay, aes(dist, delay)) +
  geom_point(aes(size = count), alpha = 1/2) +
  labs(x="Distancia (millas)", y="Retraso (mins.)") +
  geom_smooth(method = 'gam') +
  scale_size_area() +
  ggtitle("Relación entre distancia y retrasos en los vuelos") +
  scale_radius(name="Núm. vuelos")

我尝试使用

添加以下内容
nycflights13::flights$month <- month(as.Date(Date))

但是我得到了错误;     错误:找不到功能“月”

提前致谢。

1 个答案:

答案 0 :(得分:2)

月份已经在航班数据集中,所以你可以这样做:

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

    data("flights")
    by_tailnum <- group_by(.data = flights, month, tailnum)
    delay <- summarise(by_tailnum,
                       count = n(),
                       dist = mean(distance, na.rm = TRUE),
                       delay = mean(arr_delay, na.rm = TRUE))
    delay <- filter(delay, count > 20, dist < 2000)




    ggplot(delay, aes(dist, delay)) +
            geom_point(aes(size = count), alpha = 1/2) +
            labs(x="Distancia (millas)", y="Retraso (mins.)") +
            geom_smooth(method = 'gam') +
            scale_size_area() +
            ggtitle("Relación entre distancia y retrasos en los vuelos") +
            scale_radius(name="Núm. vuelos") + 
            facet_grid(month ~ .)