【问题标题】:Create a year over year plot with a month x-axis via scale_x_date() with ggplot2 [duplicate]通过带有 ggplot2 的 scale_x_date() 创建带有月份 x 轴的年复一年图 [重复]
【发布时间】: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 的答案中给出的解决方法?也许澄清一下这有什么不同,否则它看起来像重复。

标签: r ggplot2 lubridate


【解决方案1】:

这个 hack 怎么样:我们不关心 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 日期的人会出现并提供它。

【讨论】:

  • 我喜欢它,但是如果我们需要比较 9 月和 4 月(包括一年的变化),我们该怎么办。使用此解决方案,我们会在中间得到一个丑陋的差距和错误的顺序(1 月至 4 月;9 月至 12 月)。嗯……
猜你喜欢
  • 2021-08-24
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多