如何使用ggplot2的x轴日期注释?

Vic*_* K. 5 r ggplot2

我在理解轴上带有日期的绘图之间的区别时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)

带有 geom_segment 的 ggplot2 图表

但是,以下两个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 轴上没有日期的简单图表。

如果有人能解释这里到底发生了什么,我将不胜感激。

Vic*_* K. 2

看起来这是 ggplot2 中的一个错误(ggplot2 谷歌小组讨论)。我已提交新票

  • 看来这个错误又回来了……有什么进展吗? (3认同)