【问题标题】:Using lubridate and ggplot2 effectively for date axis有效地将 lubridate 和 ggplot2 用于日期轴
【发布时间】:2015-02-13 15:42:58
【问题描述】:

考虑这个例子:

library(ggplot2)
library(lubridate)

set.seed(4)
date   <- seq(from = as.POSIXct("2012-01-01"), to = as.POSIXct("2014-12-31"), by = "days")
value  <- c(rnorm(274, 50, 1), rnorm(274, 55, 1), rnorm(274, 55, 2), rnorm(274, 60, 2))
df     <- data.frame(date, value)

head(df)
#         date    value
# 1 2012-01-01 50.21675
# 2 2012-01-02 49.45751
# 3 2012-01-03 50.89114
# 4 2012-01-04 50.59598
# 5 2012-01-05 51.63562
# 6 2012-01-06 50.68928

ggplot(df, aes(x=yday(date), y=value, color=factor(year(date)))) +
  geom_line()

这会产生这个情节:

有哪些方法可以使轴按月格式化为日期?如果可能,我正在尝试确定一种干净的方式来利用 lubridatescale_x_date

也许有更好的方法来创建这种类型的图表?也就是说,按年份创建因子并将它们相互叠加? (注意:我不想在此示例中使用 facet_wrapfacet_grid)。

【问题讨论】:

    标签: r ggplot2 lubridate


    【解决方案1】:

    一种解决方案可能是向您的数据框中添加一列,该列将包含另一年中每一行的日期和月份(所有行都相同),例如 2015 年。

    df$days<-as.Date(format(df$date,"%d-%m-2015"),format="%d-%m-%y")
    

    然后您可以使用此列作为x 进行绘图

    library(scales)
    ggplot(df, aes(x=days, y=value, color=factor(year(date)))) +
      geom_line()+scale_x_date(labels = date_format("%b"))
    

    编辑:简化了df$days

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      相关资源
      最近更新 更多