ggplot2中x轴上的日期低于工作日

时间:2018-01-28 00:30:00

标签: r ggplot2

我有一个数据集,其中包含沿x轴绘制的日期(请参阅下面的完整数据集):

> head(test)
        date variable value
1 2018-01-17      foo    14
2 2018-01-18      foo    18
3 2018-01-19      foo    22
4 2018-01-20      foo    15
5 2018-01-21      foo    32
6 2018-01-22      foo    27

我的目标是将第二行x轴标签(星期几)包含在当前日期之下。

但是,当我在ggplot中包含注释时,会抛出错误。有人可以建议一个解决方法吗?

ggplot(data=test,
       aes(x=date, y=value, colour=variable)) +
       geom_line() + geom_text(aes(label=value),hjust=0, vjust=0) + 
      annotate(geom = "text", x=date, y= -2, label = weekdays(test$date), size = 4, angle = 90)

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 0, 1

以下是示例数据:

> dput(test)
structure(list(date = structure(c(17548, 17549, 17550, 17551, 
17552, 17553, 17554, 17555, 17556, 17557, 17558, 17548, 17549, 
17550, 17551, 17552, 17553, 17554, 17555, 17556, 17557, 17558
), class = "Date"), variable = c("foo", "foo", "foo", "foo", 
"foo", "foo", "foo", "foo", "foo", "foo", "foo", "bar", "bar", 
"bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar", "bar"
), value = c(14L, 18L, 22L, 15L, 32L, 27L, 6L, 3L, 2L, 10L, 23L, 
16L, 22L, 28L, 31L, 56L, 57L, 23L, 17L, 12L, 33L, 54L)), row.names = c(NA, 
-22L), .Names = c("date", "variable", "value"), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

您可以使用scale_x_date的{​​{1}}参数来传递date_labels样式标记的解析字符串,其中可以包含strptime等文字。可以通过传递\ndate_breaks参数字符串来设置中断。

seq.Date

weekdays on axis