[英]R sort by Year then Month in ggplot2
If you look at my df_summary_mo table it is nicely arranged first by year, then by month. 如果您查看我的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
By default ggplot2 sorts this particular graph (code below) in a format that places the months numerically in order (1,2,3,4...). 默认情况下,ggplot2将该特定的图形(以下代码)排序,该格式将月份按数字顺序排列为(1,2,3,4 ...)。 How do I get the graph to place the 2017 months before the 2018 months? 如何将图表放在2017个月之前的2017个月? I messed around with the reorder argument but it doesn't seem to help. 我弄乱了reorder参数,但似乎无济于事。
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()
I would define yearmon
so that the order works automatically... 我将定义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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.