【发布时间】:2016-10-04 20:16:59
【问题描述】:
考虑以下数据:
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
我想制作一个“年复一年”的情节,并将颜色分配给年份。我可以通过以下方式做到这一点:
ggplot(df, aes(x = yday, y = value, color = factor(year))) +
geom_line()
但这会导致 x 轴是“一年中的一天”而不是月份标签。添加+ 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")
但要让岁月“堆积”在同一个情节上。
【问题讨论】:
-
我认为您不想使用previous question 的答案中给出的解决方法?也许澄清一下这有什么不同,否则它看起来像重复。