【问题标题】:R - Formatting data per month and facet wrapping per yearR - 每月格式化数据和每年分面包装
【发布时间】:2020-06-14 19:43:06
【问题描述】:

我正在使用 R 进行练习,并且在尝试创建每月航空公司乘客图表时遇到了障碍。

我想显示从 1949 年到 1960 年的每一年的单独月线图,据此记录数据。为此,我使用 ggplot 创建了一个包含每月值的折线图。这很好用,但是当我尝试使用 facet_wrap() 将其按年分开并格式化当前的month 字段时:facet_wrap(format(air$month[seq(1, length(air$month), 12)], "%Y"));它返回这个:

Graph returned

我还尝试通过输入我自己多年来的序列来格式化构面:rep(c(1949:1960), each = 12)。这会返回一个更好但仍然错误的不同结果:

Second graph

这是我的代码:

air = data.frame(
  month = seq(as.Date("1949-01-01"), as.Date("1960-12-01"), by="months"),
  air = as.vector(AirPassengers)
)


ggplot(air, aes(x = month, y = air)) +
  geom_point() +
  labs(x = "Month", y = "Passengers (in thousands)", title = "Total passengers per month, 1949 - 1960") +
  geom_smooth(method = lm, se = F) + 
  geom_line() +
  scale_x_date(labels = date_format("%b"), breaks = "12 month") +
  facet_wrap(format(air$month[seq(1, length(air$month), 12)], "%Y"))
#OR
  facet_wrap(rep(c(1949:1960), each = 12))

那么我如何每年制作一张单独的图表?

谢谢!

【问题讨论】:

    标签: r ggplot2 facet-wrap


    【解决方案1】:

    在第二次尝试中,你真的很接近。数据的主要问题是您正在尝试使用不同的 x 轴值(包括年份的日期)制作多面图。解决此问题的一个简单解决方案是将数据转换为“通用”x 轴刻度,然后绘制多面图。这是应该输出所需绘图的代码。

    library(tidyverse)
    library(lubridate)
    
    air %>%
      # Get the year value to use it for the facetted plot
      mutate(year = year(month),
             # Get the month-day dates and set all dates with a dummy year (2021 in this case)
             # This will get all your dates in a common x axis scale
             month_day = as_date(paste(2021,month(month),day(month), sep = "-"))) %>%
      # Do the same plot, just change the x variable to month_day
      ggplot(aes(x = month_day, 
                 y = air)) +
      geom_point() +
      labs(x = "Month", 
           y = "Passengers (in thousands)", 
           title = "Total passengers per month, 1949 - 1960") +
      geom_smooth(method = lm, 
                  se = F) + 
      geom_line() +
      # Set the breaks to 1 month
      scale_x_date(labels = scales::date_format("%b"), 
                   breaks = "1 month") +
      # Use the year variable to do the facetted plot
      facet_wrap(~year) +
      # You could set the x axis in an 90° angle to get a cleaner plot
      theme(axis.text.x = element_text(angle = 90,
                                       vjust = 0.5,
                                       hjust = 1))
    

    【讨论】:

    • 太棒了,完美运行!谢谢你。问题一:变异的时候为什么要加year = year(month)?在我未经训练的眼睛看来,它似乎并没有改变数据框的任何内容。谢谢!
    • year 是来自lubridate 包的函数,它获取日期的年份(在本例中,即名为“月”的列)。所以year = year(month) 行实际上是在创建一个名为“year”的新列,其中包含您的日期列的年份。
    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2020-03-14
    • 2019-09-07
    • 2021-06-19
    相关资源
    最近更新 更多