ggplot 使用分组日期变量(例如 year_month)
ggplot using grouped date variables (such as year_month)
我觉得这对 ggplot
、tidyverse
、lubridate
来说应该是一件容易的事,但我似乎找不到一个优雅的解决方案。
目标:创建我的数据 aggregated/summarized/grouped_by 年和月的条形图。
#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 轴。也许这可以通过将日期设置为每月的第一天来解决...?
你们真的很亲密。缺少的部分是 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")
我觉得这对 ggplot
、tidyverse
、lubridate
来说应该是一件容易的事,但我似乎找不到一个优雅的解决方案。
目标:创建我的数据 aggregated/summarized/grouped_by 年和月的条形图。
#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 轴。也许这可以通过将日期设置为每月的第一天来解决...?
你们真的很亲密。缺少的部分是 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")