我在理解轴上带有日期的绘图之间的区别时geom_segment遇到问题。annotate(segment, ...)x
让我们从一些随机数据开始:
library(data.table)
library(lubridate)
library(ggplot2)
# Prepare some random data
set.seed(1234)
dt <- data.table(x = rnorm(365*5), d = seq(ymd(20130101), ymd(20131231), by = 86400))
dt.m <- dt[, list(total = sum(x)), by = list(month = floor_date(d, "month"))]
# Create a basic scatterplot chart
p <- qplot(month, total, data = dt.m)
Run Code Online (Sandbox Code Playgroud)
以下两项都可以工作并向上面定义的绘图添加一个线段p:
# Both of these work as expected and produce the same result
p + geom_segment(x = as.numeric(ymd(20130401)), xend = as.numeric(ymd(20130701)),
y = -10, yend = 10)
p + geom_segment(aes(x = ymd(20130401), xend = ymd(20130701),
y = -10, yend = 10))
Run Code Online (Sandbox Code Playgroud)

但是,以下两个annotate("segment", ...)调用都不起作用 - 并且它们会产生不同的错误消息,我无法真正解析这些消息。
> p + annotate("segment", x = as.numeric(ymd(20130401)), xend = as.numeric(ymd(20130701)),
y = -10, yend = 10)
Error: Invalid input: time_trans works with objects of class POSIXct only
> p + annotate("segment", x = ymd(20130401), xend = ymd(20130701),
y = -10, yend = 10)
Error in Ops.POSIXt((x - from[1]), diff(from)) :
'/' not defined for "POSIXt" objects
> p + annotate("segment", aes(x = ymd(20130401), xend = ymd(20130701),
y = -10, yend = 10))
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) :
cannot coerce class ""uneval"" to a data.frame
Run Code Online (Sandbox Code Playgroud)
我annotate("segment", ...)在 R Graphics Cookbook 中对收到 7.4 后的调用进行了建模,它似乎可以很好地处理 x 轴上没有日期的简单图表。
如果有人能解释这里到底发生了什么,我将不胜感激。