2017-10-11 41 views
0

如果你看一下我的df_summary_mo表它是很好的安排首先按年,然后通过一个月。R按年则月在GGPLOT2

 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 

通过在放置几个月数值以(1,2,3,4 ......)的格式默认排序GGPLOT2这个特殊的图(下面的代码)。 2018年之前的2017年,我如何获得图表?我搞砸了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() 

回答

0

我会定义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() 

enter image description here

+0

添加到由@AndrewGustar给出了答案,x轴的标签可以通过使用旋转,''element_text()''调用'ggplot()',就像'ggplot(df_summary_mo,aes(yearmon,total,fill = year))+ geom_col()+ theme(axis.text.x = element_text(angle = 65,hjust = 1))'。这样,“x轴”标签就不会重叠。 – Ashish