通过 scale_x_date() 和 ggplot2 创建一个带有月份 x 轴的年同比图
Create a year over year plot with a month x-axis via scale_x_date() with ggplot2
考虑以下数据:
library(ggplot2)
library(lubridate)
date <- seq.Date(ymd("2015-01-01"), Sys.Date(), by = "day")
df <- data.frame(date = date,
value = seq_along(date) + rnorm(length(date), sd = 100))
# Add yday and year
df$yday <- yday(df$date)
df$year <- year(df$date)
head(df)
# date value yday year
# 1 2015-01-01 97 1 2015
# 2 2015-01-02 89 2 2015
# 3 2015-01-03 68 3 2015
# 4 2015-01-04 57 4 2015
# 5 2015-01-05 70 5 2015
# 6 2015-01-06 100 6 2016
我想制作一个 "year over year" 绘图,并将颜色分配给年份。我可以通过以下方式做到这一点:
ggplot(df, aes(x = yday, y = value, color = factor(year))) +
geom_line()
但这会导致 x 轴成为 "day of the year" 而不是月份标签。添加 + scale_x_date()
失败,因为 yday
不再是日期。
是否可以使用scale_x_date()
?
归根结底,我想做这样的事情:
ggplot(df, aes(x = date, y = value, color = factor(year))) +
geom_line() +
scale_x_date(date_labels = "%b")
但保持年份 "stacked" 在同一个地块上。
这个 hack 怎么样:我们不关心 yday
是哪一年,所以只需将其转换回 Date
格式(在这种情况下,年份将始终为 1970,无论给定 yday
来自的实际年份)并仅显示 x 轴标签的月份。
您实际上不需要向数据框添加 yday
或 year
列,因为您可以在 ggplot 调用中即时创建它们。
ggplot(df, aes(x = as.Date(yday(date), "1970-01-01"), y = value,
color = factor(year(date)))) +
geom_line() +
scale_x_date(date_breaks="months", date_labels="%b") +
labs(x="Month",colour="") +
theme_bw()
可能有更简洁的方法,希望更熟练使用 R 日期的人会出现并提供它。
考虑以下数据:
library(ggplot2)
library(lubridate)
date <- seq.Date(ymd("2015-01-01"), Sys.Date(), by = "day")
df <- data.frame(date = date,
value = seq_along(date) + rnorm(length(date), sd = 100))
# Add yday and year
df$yday <- yday(df$date)
df$year <- year(df$date)
head(df)
# date value yday year
# 1 2015-01-01 97 1 2015
# 2 2015-01-02 89 2 2015
# 3 2015-01-03 68 3 2015
# 4 2015-01-04 57 4 2015
# 5 2015-01-05 70 5 2015
# 6 2015-01-06 100 6 2016
我想制作一个 "year over year" 绘图,并将颜色分配给年份。我可以通过以下方式做到这一点:
ggplot(df, aes(x = yday, y = value, color = factor(year))) +
geom_line()
但这会导致 x 轴成为 "day of the year" 而不是月份标签。添加 + scale_x_date()
失败,因为 yday
不再是日期。
是否可以使用scale_x_date()
?
归根结底,我想做这样的事情:
ggplot(df, aes(x = date, y = value, color = factor(year))) +
geom_line() +
scale_x_date(date_labels = "%b")
但保持年份 "stacked" 在同一个地块上。
这个 hack 怎么样:我们不关心 yday
是哪一年,所以只需将其转换回 Date
格式(在这种情况下,年份将始终为 1970,无论给定 yday
来自的实际年份)并仅显示 x 轴标签的月份。
您实际上不需要向数据框添加 yday
或 year
列,因为您可以在 ggplot 调用中即时创建它们。
ggplot(df, aes(x = as.Date(yday(date), "1970-01-01"), y = value,
color = factor(year(date)))) +
geom_line() +
scale_x_date(date_breaks="months", date_labels="%b") +
labs(x="Month",colour="") +
theme_bw()
可能有更简洁的方法,希望更熟练使用 R 日期的人会出现并提供它。