简体   繁体   English

ggplot2:如何将文本添加到时间x轴上的多个垂直线(geom_vlines)?

[英]ggplot2: how to add text to multiple vertical lines (geom_vlines) on a time x-axis?

Please have a look at the following example 请看下面的例子

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?

I would like to get a line chart for the variable value for each group (A and B) and plot vertical lines every time there is an event in the events dataframe. 我想获取每个组(A和B)的变量value的折线图,并在events数据帧中每次发生事件时绘制垂直线。

Using the ideas ggplot vertical line with date axis , How to get a vertical geom_vline to an x-axis of class date? 使用带有日期轴的ggplot垂直线想法, 如何将垂直geom_vline设置为班级日期的x轴? and How to add legend for vertical lines in ggplot? 以及如何在ggplot中为垂直线添加图例? I can easily do that: 我可以轻松做到这一点:

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

在此处输入图片说明

The problem is that I would like to label each vertical line (each event) with the corresponding text, as in R ggplot2: Labelling a horizontal line on the y axis with a numeric value . 问题是,我想用相应的文本标记每个垂直线(每个事件),如R ggplot2所示:在y轴上用数字值标记水平线

Unfortunately, doing the following does not work 不幸的是,执行以下操作无效

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

What is wrong here? 怎么了 any ideas? 有任何想法吗? Thanks! 谢谢!

You can try 你可以试试

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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM