gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:34:20 27 4
gpt4 key购买 nike

请看下面的例子

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?

我想获得变量 value 的折线图对于每组(A 和 B),每次在 events 中发生事件时绘制垂直线数据框。

使用思路 ggplot vertical line with date axis , How to get a vertical geom_vline to an x-axis of class date?How to add legend for vertical lines in 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)))

enter image description here

问题是我想用相应的文本标记每个垂直线(每个事件),如 R ggplot2: Labelling a horizontal line on the y axis with a numeric value .

不幸的是,执行以下操作不起作用
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))

这里有什么问题?有任何想法吗?
谢谢!

最佳答案

你可以试试

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)

enter image description here

关于r - ggplot2:如何将文本添加到时间 x 轴上的多条垂直线(geom_vlines)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41231903/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com