This question already has an answer here:
Using lubridate and ggplot2 effectively for date axis

(1个答案)


4年前关闭。




考虑以下数据:
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()

r - 通过带有ggplot2的scale_x_date()创建带有月x轴的按年绘制图-LMLPHP

但这导致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")

但是,要把岁月“堆积”在同一块土地上。

最佳答案

骇客如何处理:我们不在乎yday的年份,所以只需将其转换回Date格式(在这种情况下,年份始终为1970,而与给定yday的实际年份无关),仅显示x轴标签的月份。

您实际上不需要在数据框中添加ydayyear列,因为您可以在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日期并提供它。

r - 通过带有ggplot2的scale_x_date()创建带有月x轴的按年绘制图-LMLPHP

08-25 02:14