2017-10-11 37 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