ggplot2中x轴上日期以下的工作日

the*_*ide 4 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
Run Code Online (Sandbox Code Playgroud)

我的目标是在当前仅显示日期的标签下方包含第二行 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
Run Code Online (Sandbox Code Playgroud)

这是示例数据:

> 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")
Run Code Online (Sandbox Code Playgroud)

ali*_*ire 6

您可以使用scale_x_datedate_labels参数来传递一个解析字符串的strptime样式标记,其中可以包括像\n. 可以通过传递date_breaks参数字符串来设置中断seq.Date

library(ggplot2)

test <- data.frame(date = as.Date(c("2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20","2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27", "2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20", "2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27")), 
                   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),
                   stringsAsFactors = FALSE)

ggplot(test, aes(date, value, colour = variable, label = value)) +
    geom_line() + 
    geom_text(hjust = 0, vjust = 0, show.legend = FALSE) + 
    scale_x_date(date_breaks = 'day', 
                 date_labels = '%b %d\n%a')
Run Code Online (Sandbox Code Playgroud)

轴上的工作日