coord_cartesian with dates, date/times

2,515 views
Skip to first unread message

d.c.c...@its.leeds.ac.uk

unread,
Apr 27, 2009, 3:58:04 PM4/27/09
to ggplot2
Dear all,

I would like to use coord_cartesian to zoom in on a part of a time
series, but cannot seem to do it.

Taking a similar example to Hadley's from the ggplot2 web pages:

df <- data.frame(date = seq(Sys.Date(), len=100, by="1 day")[sample
(100, 50)], price = runif(50))
df <- df[order(df$date), ]
qplot(date, price, data=df, geom="line")

plots a nice time series.

To extract part of it, which also works:

qplot(date, price, data=df, geom="line") + scale_x_date(limits = c
(as.Date("2009-04-27"), as.Date("2009-06-09")))

But what if I just want to zoom in on a date range (scale_x_date will
drop data outside the range)? I had thought this would work:

qplot(date, price, data=df, geom="line") + coord_cartesian(xlim = c
(as.Date("2009-04-27"), as.Date("2009-06-09")))

but returns the error:
Error in `-.Date`(x, from[1]) : Can only subtract from Date objects

Does coord_cartesian work with Date or POSIXct classes, or am I
missing something? It would be nice if it did.

Thanks!

David

hadley wickham

unread,
Apr 27, 2009, 4:50:40 PM4/27/09
to d.c.c...@its.leeds.ac.uk, ggplot2
On Mon, Apr 27, 2009 at 2:58 PM, <d.c.c...@its.leeds.ac.uk> wrote:
>
> Dear all,
>
> I would like to use coord_cartesian to zoom in on a part of a time
> series, but cannot seem to do it.
>
> Taking a similar example to Hadley's from the ggplot2 web pages:
>
> df <- data.frame(date = seq(Sys.Date(), len=100, by="1 day")[sample
> (100, 50)], price = runif(50))
> df <- df[order(df$date), ]
> qplot(date, price, data=df, geom="line")
>
> plots a nice time series.
>
> To extract part of it, which also works:
>
> qplot(date, price, data=df, geom="line") + scale_x_date(limits = c
> (as.Date("2009-04-27"), as.Date("2009-06-09")))
>
> But what if I just want to zoom in on a date range (scale_x_date will
> drop data outside the range)?  I had thought this would work:
>
> qplot(date, price, data=df, geom="line") + coord_cartesian(xlim = c
> (as.Date("2009-04-27"), as.Date("2009-06-09")))

Try this:

coord_cartesian(xlim = as.numeric(as.Date(c("2009-04-27", "2009-06-09"))))

By the time the date gets to the coordinate system, it has been
converted to a numeric, so coord_cartesian needs numeric limits. In
an ideal world, you'd be able to zoom in by just dragging the mouse
around, so it wouldn't be a problem. Unfortunately R graphics doesn't
make that easy.

Hadley

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

Reply all
Reply to author
Forward
0 new messages