Jef*_*ker 5 r ggplot2 lubridate dplyr tidyverse
我觉得这应该是一件容易的事了ggplot,tidyverse,lubridate,但我似乎无法找到一个很好的解决方案.
目标:根据年份和月份创建汇总/汇总/分组数据的条形图.
#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')
Run Code Online (Sandbox Code Playgroud)
当我创建year_month变量时,它自然变成一个字符变量而不是一个日期变量.我也试过分组,year(date), month(date)但后来我无法弄清楚如何使用两个变量作为x轴ggplot.也许这可以通过将日期安排到本月的第一天来解决......?
你真的很亲密.缺失的部分是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")
Run Code Online (Sandbox Code Playgroud)