我有一個日期串列,我需要按月和年(2020 年 3 月、2020 年 4 月等)報告它們。但是,當我從日期決議月份和年份時,我得到一個字串而不是日期,所以當我嘗試將其繪制到 ggplot 中時,順序是字母順序而不是時間順序。
我知道我可以手動指定一個帶有因子的訂單,但是輸入每個月和年的組合會很痛苦——有沒有更有效的方法來解決這個問題?我嘗試將我的日期包含在my()fromlubridate中,但這沒有用。
#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()

uj5u.com熱心網友回復:
該reorder函式(stats 包)可用于對因子水平進行排序。在這里,您可以使用my第二個引數來確定排序順序。所以我相信這可以滿足您的需求:
ggplot(test, aes(x = reorder(month, my(month)), y = values)) geom_col()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/445310.html
上一篇:使用系列替換交換列時如何用mutate替換mutate_?
下一篇:替換資料框中的相同變數
