ggplot2:如何在时间x轴上向多条垂直线(geom_vlines)添加文本?

ℕʘʘ*_*ḆḽḘ 5 r ggplot2

请看下面的例子

library(dplyr)
library(lubridate)
library(ggplot2)
data <- data_frame(time = c(ymd(20160201),
                            ymd(20160202),
                            ymd(20160203),
                            ymd(20160201),
                            ymd(20160202)),
                            value = c(1,1,1,2,2), 
                            group = c('A','A','B','B','B'))

events <- data_frame(time = c(ymd(20160201), 
                              ymd(20160202)),
                     text = c('who let the dogs out?',
                              'who? who? who?'))

ggplot(data, aes(x = time, y = value, group = group, color = group)) + 
  geom_line(size = 2 ) +
  geom_vline(data = events, aes(xintercept = as.numeric(time)))  

> data
# A tibble: 5 × 3
        time value group
      <date> <dbl> <chr>
1 2016-02-01     1     A
2 2016-02-02     1     A
3 2016-02-03     1     B
4 2016-02-01     2     B
5 2016-02-02     2     B

> events
# A tibble: 2 × 2
        time                  text
      <date>                 <chr>
1 2016-02-01 who let the dogs out?
2 2016-02-02        who? who? who?
Run Code Online (Sandbox Code Playgroud)

我想获得value每个组(A和B)的变量的折线图,并在每次events数据帧中有事件时绘制垂直线.

使用ggplot垂直线与日期轴的想法 ,如何将一个垂直geom_vline到类日期的x轴?以及如何在ggplot中为垂直线添加图例?我可以轻松地做到这一点:

ggplot(data, aes(x = time, y = value, group = group, color = group)) + 
  geom_line(size = 2 ) +
  geom_vline(data = events, aes(xintercept = as.numeric(time)))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

问题是我想用相应的文本标记每条垂直线(每个事件),如在R ggplot2中:在y轴上用数字值标记水平线.

不幸的是,执行以下操作无效

ggplot(data, aes(x = time, y = value, group = group, color = group)) + 
  geom_line(size = 2 ) +
  geom_vline(data = events, aes(xintercept = as.numeric(time)))  +
  geom_text(data = events, aes(x = as.numeric(time), y = 0, label = text))
Run Code Online (Sandbox Code Playgroud)

这有什么不对?有任何想法吗?谢谢!

luk*_*keA 9

你可以试试

ggplot(data, aes(x = time)) + 
  geom_line(aes(y = value, group = group, color = group), size = 2 ) +
  geom_vline(data = events, aes(xintercept = as.numeric(time)))  +
  geom_text(data = events, mapping = aes(label = text, y = 0), angle = 60, hjust = 0)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我喜欢使用`y = -Inf`来保持'ylims`的响应.像这样的东西`geom_text(data = events,aes(label = text,x = time,y = -Inf),angle = 90,inherit.aes = F,hjust = -.5,vjust = -.5)` (3认同)
  • 你需要忘记`group = group`,因为变量`events $ group`不存在而且`geom_text`正在寻找它.你可以改为设置`group = NULL`.`geom_vline`不会查找它,因此不会引发错误. (3认同)