value for xintercept argument of geom_vline() with a date axis

2,798 views
Skip to first unread message

James Kebinger

unread,
Jan 6, 2010, 4:35:29 PM1/6/10
to ggplot2
Hi, I was doing what I thought would be simple, adding a vertical line to a line chart at a date, but doing any of the following
geom_vline(xintercept='2009-12-21'))
geom_vline(xintercept=ISOdate(2009,12,21))

didn't work. I eventually figured out that if I passed an integer 0, it was in 1970, so this was days since the epoch, so by trial and error I got the chart done like this:

ggplot(z,aes(x=date,y=fraction_viewing_feature)) + geom_line() + scale_x_date() + geom_vline(xintercept = 14600-1, color="red")

Should this xintercept argument accept some form of a date that I overlooked? Failing that, is there a simple way to derive days since the epoch for a date?

thanks!

-james

Brian Diggs

unread,
Jan 7, 2010, 11:08:21 AM1/7/10
to ggplot2
The format of dates that ggplot2 uses are the Date class which, as you
figured out, is the number of days since 1970-01-01.

To make your example reproducible, I had to create a dummy data.frame
z:

z <- structure(list(date = structure(c(14598, 14600), class =
"Date"),
fraction_viewing_feature = c(0.3, 0.5)), .Names = c("date",
"fraction_viewing_feature"), row.names = c(NA, -2L), class =
"data.frame")

Then either of the following will work:

ggplot(z,aes(x=date,y=fraction_viewing_feature)) + geom_line() +
scale_x_date() + geom_vline(aes(xintercept=as.Date("2009-12-21")),
color="red")

or

ggplot(z,aes(x=date,y=fraction_viewing_feature)) + geom_line() +
scale_x_date() + geom_vline(xintercept=unclass(as.Date("2009-12-21")),
color="red")

The unclass(as.Date(...)) construct is what you asked for a way to
derive the number of days since the epoch.

--Brian Diggs

hadley wickham

unread,
Jan 7, 2010, 11:13:22 AM1/7/10
to Brian Diggs, ggplot2
> ggplot(z,aes(x=date,y=fraction_viewing_feature)) + geom_line() +
> scale_x_date() + geom_vline(xintercept=unclass(as.Date("2009-12-21")),
> color="red")
>
> The unclass(as.Date(...)) construct is what you asked for a way to
> derive the number of days since the epoch.

A slightly better (i.e. more general approach) is as.numeric(as.Date(...))

Hadley


--
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages