R - 每月格式化数据和每年分面包装

R - Formatting data per month and facet wrapping per year

我正在练习 R 并在尝试创建每月航空公司乘客图表时遇到了减速带。

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

Graph returned

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

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

那么我如何制作每年的个人图表?

谢谢!

在第二次尝试中,你真的很接近。数据的主要问题是您正在尝试制作具有不同 x 轴值(包括年份的日期)的多面图。一个简单的解决方案是将数据转换为 "common" 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))