如何将文本注释添加到时间序列ggplot
How to add a text annotations to a time series ggplot
我知道 annotate() 并且您需要添加 x 和 y 坐标。问题是我的 x 是 class ""POSIXct" "POSIXt." 所以当我尝试使用注释时,R 响应,对象需要是 POSIXct。我已经尝试了各种组合来修复这个 .. .没有成功。有什么想法吗?
确保注释中的 x 参数编码为 POSIXct。例如,使用 lattice 包中的大麦数据集,我们可以将年份重新编码为 POSIXct,然后注释:
library(lattice)
library(tidyverse)
barley %>%
#convert year from factor to numeric, and then to POSIXct
mutate(year = as.numeric(levels(year))[year],
year = as.POSIXct(paste0(year, "-01-01"))) %>%
group_by(year) %>%
summarise(AvgYield = mean(yield)) %>%
ggplot(aes(year, AvgYield)) +
geom_line() +
#now to annotate, just make sure to code x as POSIXct
#in a range that will appear on the plot
annotate("text", x = as.POSIXct("1931-04-01"), y = 34, label = "Some text")
我知道 annotate() 并且您需要添加 x 和 y 坐标。问题是我的 x 是 class ""POSIXct" "POSIXt." 所以当我尝试使用注释时,R 响应,对象需要是 POSIXct。我已经尝试了各种组合来修复这个 .. .没有成功。有什么想法吗?
确保注释中的 x 参数编码为 POSIXct。例如,使用 lattice 包中的大麦数据集,我们可以将年份重新编码为 POSIXct,然后注释:
library(lattice)
library(tidyverse)
barley %>%
#convert year from factor to numeric, and then to POSIXct
mutate(year = as.numeric(levels(year))[year],
year = as.POSIXct(paste0(year, "-01-01"))) %>%
group_by(year) %>%
summarise(AvgYield = mean(yield)) %>%
ggplot(aes(year, AvgYield)) +
geom_line() +
#now to annotate, just make sure to code x as POSIXct
#in a range that will appear on the plot
annotate("text", x = as.POSIXct("1931-04-01"), y = 34, label = "Some text")