如何让 R 识别月年组合的适当顺序,而无需手动指定顺序?
我有一个日期列表,我需要按月份和年份报告它们(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()
I have a list of dates, and I need to report them by month and year (Mar 2020, Apr 2020, etc). However, when I parse the Month and Year from the date, I get a character string instead of a date, so when I try to plot it into ggplot, the order is alphabetical instead of chronological.
I know I can manually specify an order with factor, but typing out every month and year combination will be painful--is there a more efficient way to tackle this problem? I tried wrapping my date in my()
from lubridate
, but that didn't work.
#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()
Here's a simple plot showing that the order is alphabetical instead of chronological
#Simple plot showing that the order is alphabetical instead of chronological
library(ggplot2)
ggplot(test, aes(x = month, y = values)) +
geom_col()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
reorder
函数(stats 包)可用于对因子级别进行排序。在这里,您可以在第二个参数中使用my
来确定排序顺序。所以我相信这可以满足您的需要:The
reorder
function (stats package) can be used to sort factor levels. Here you can usemy
in the second argument to determine the sort order. So I believe this does what you need: