2017-11-27 24 views
3

私はこれがggplottidyverselubridateの簡単な作業でなければならないと感じていますが、私は洗練された解決策を見つけることはできません。グループ化された日付変数(year_monthなど)を使用しているggplot

目標:年と月を集計/集計/グループ化したデータの棒グラフを作成します。

#Libraries 
library(tidyverse) 
library(lubridate) 

# Data 
date <- sample(seq(as_date('2013-06-01'), as_date('2014-5-31'), by="day"), 10000, replace = TRUE) 
value <- rnorm(10000) 
df <- tibble(date, value) 

# Summarise 
df2 <- df %>% 
    mutate(year = year(date), month = month(date)) %>% 
    unite(year_month,year,month) %>% 
    group_by(year_month) %>% 
    summarise(avg = mean(value), 
      cnt = n()) 
# Plot 
ggplot(df2) + 
    geom_bar(aes(x=year_month, y = avg), stat = 'identity') 

year_month変数を作成すると、自然に日付変数の代わりに文字変数になります。私はyear(date), month(date)でグループ化を試みましたが、ggplotのx軸として2つの変数を使用する方法を理解できません。おそらくこれは月の最初の日に日付をフローリングすることで解決できます...?

答えて

5

本当に近いです。欠けている部分はfloor_date()scale_x_date()です:

library(tidyverse) 
library(lubridate) 

date <- sample(seq(as_date('2013-06-01'), as_date('2014-5-31'), by = "day"), 
    10000, replace = TRUE) 
value <- rnorm(10000) 

df <- tibble(date, value) %>% 
    group_by(month = floor_date(date, unit = "month")) %>% 
    summarize(avg = mean(value)) 

ggplot(df, aes(x = month, y = avg)) + 
    geom_bar(stat = "identity") + 
    scale_x_date(NULL, date_labels = "%b %y", breaks = month) 

enter image description here