R-每月格式化数据,每年进行小平面包装

问题描述 投票:0回答:1

我正在使用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个回答
0
投票

在第二次尝试中,您真的很接近。数据的主要问题是您试图制作具有不同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))

Plot facet by year

© www.soinside.com 2019 - 2024. All rights reserved.