如何在不手动指定顺序的情况下让 R 识别月年组合的适当顺序?

How do I get R to recognize the appropriate order for Month Year combinations without manually specifying the order?

我有一个日期列表,我需要按月和年(2020 年 3 月、2020 年 4 月等)报告它们。但是,当我从日期解析月份和年份时,得到的是字符串而不是日期,因此当我尝试将其绘制到 ggplot 中时,顺序是按字母顺序而不是时间顺序。

我知道我可以手动指定一个带有因子的顺序,但是输入每个月和年的组合会很痛苦——有没有更有效的方法来解决这个问题?我尝试将我的日期从 lubridate 包装在 my() 中,但这没有用。

#My sample data
library(dplyr)

test <- tibble(date = seq(ymd('2021-01-01'), ymd('2021-12-31'), by = "1 day"),
                              values = c(1001:1182, 800:900, 1:82),
                              month = cut.Date(date, breaks = "1 month", labels = FALSE)) %>%
  group_by(month) %>%
  mutate(month = format(last(date), '%b %Y')) %>%
  ungroup()

这是一个简单的图表,显示顺序是按字母顺序而不是按时间顺序排列的

#Simple plot showing that the order is alphabetical instead of chronological

library(ggplot2)
ggplot(test, aes(x = month, y = values)) +
  geom_col()

reorder 函数(stats 包)可用于对因子水平进行排序。这里可以在第二个参数中使用 my 来确定排序顺序。所以我相信这可以满足您的需求:

ggplot(test, aes(x = reorder(month, my(month)), y = values)) + geom_col()