Reputation: 4094
I have a problem understanding the difference between geom_segment
and annotate(segment, ...)
when it comes to plots with dates on the x
axis.
Let's start with some random data:
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)
Both of the following work and add a segment to the plot p
defined above:
# 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))
However, neither of the following annotate("segment", ...)
calls work - and they produce different error messages, which I cannot really parse.
> 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
I modelled the annotate("segment", ...)
calls after receipt 7.4 in R Graphics Cookbook, and it seems to work fine with simple graphs that have no dates in x-axis.
I would appreciate if someone can explain what's really going on here.
Upvotes: 5
Views: 4927
Reputation: 4094
Looks like it's a bug in ggplot2 (ggplot2 google groups discussion). I have submitted a new ticket.
Upvotes: 2