如果你看一下我的 df_summary_mo 表,它会按年顺序排列,然后逐月排列。
year month total
<fctr> <chr> <dbl>
1 2017 10 11.02006
2 2017 11 16.62367
3 2017 12 14.84555
4 2018 01 14.61277
5 2018 02 14.06558
6 2018 03 15.73514
7 2018 04 14.51999
8 2018 05 14.33848
9 2018 06 13.49925
10 2018 07 14.04433
11 2018 08 3.88255
默认情况下,ggplot2以一种格式对这个特定图形(下面的代码)进行排序,该数字按月排序(1,2,3,4 ...)。如何将图表放在2018年之前的2017个月?我搞砸了 重新排序 这个论点,但它似乎没什么帮助。
library(dplyr)
library(lubridate)
df <- data.frame(date = today() + days(1:300), value = runif(300))
df_summary_mo <- df %>%
mutate(year = format(date, "%Y"), month = format(date, "%m")) %>%
group_by(year, month) %>%
summarise(total = sum(value))
ggplot(df_summary_mo, aes(month, total, fill=year, reorder(year,month))) + geom_col()
答案 0 :(得分:1)
我会定义yearmon
,以便订单自动生效...
df_summary_mo <- df %>%
mutate(year = format(date, "%Y"), yearmon = format(date, "%Y-%m")) %>%
group_by(year, yearmon) %>%
summarise(total = sum(value))
ggplot(df_summary_mo, aes(yearmon, total, fill=year)) + geom_col()