r - 对日期轴有效地使用 lubridate 和 ggplot2

标签 r ggplot2 lubridate

考虑这个例子:

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()

生成这个图:

Plot

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

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

最佳答案

一种解决方案可能是向您的数据框中添加一列,该列将包含另一年中每一行的日期和月份(所有行都相同),例如 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"))

enter image description here

编辑:简化 df$days线

关于r - 对日期轴有效地使用 lubridate 和 ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28503262/

相关文章:

r - 如何对每个唯一因子值使用一次应用函数

r - 点阵,仅当连接具有正斜率时才连接点

r - 将一列信息输入到 R 数据框中。

r - 在 R 中使函数可循环

r - 我如何寻求有关 ggplot2 R 包参数的帮助

R 如果实际数字是 1,那么从日期获取上一周数字的最佳方法是什么

r - Unstack lubridate 的间隔类

r - 使用 R 显示跨面密度的主要峰值

r - 为 ggplot 2.2.0 破坏的 gtable_add_grob 代码寻求解决方法

R:if_else 和时区强制