scale_x_continous and POSIX times

1,078 views
Skip to first unread message

neuwirthe

unread,
Apr 26, 2016, 11:29:24 AM4/26/16
to ggplot2
I would like to control minor breaks on an x axis with time values.

Just using a POSX variable with POSIXct values works fine.

But when I try

basetime <- as.numeric(as.POSIXct("2016-04-24 12:00:00 CEST",origin = "1582-10-14", tz = "GMT"))
and, as part of the ggplot call
scale_x_continuous(minor_breaks = as.POSIXct(basetime + (0:9)*3600,origin= "1970-01-01",tz="GMT"))

I get the error

Error in as.POSIXct.numeric(value) : 'origin' must be supplied

How can I get minor breaks to work with POSIXct values?


Brian

unread,
Apr 26, 2016, 1:46:13 PM4/26/16
to neuwirthe, ggplot2
Hi Erich,

why do you convert the POSIXt object back to numeric?
Try:

> basetime <- as.POSIXct("2016-04-24 12:00:00 CEST",origin =
"1582-10-14", tz = "GMT")
+ > basetime
[1] "2016-04-24 12:00:00 GMT"

> basetime + (0:9)*3600
[1] "2016-04-24 12:00:00 GMT" "2016-04-24 13:00:00 GMT"
[3] "2016-04-24 14:00:00 GMT" "2016-04-24 15:00:00 GMT"
[5] "2016-04-24 16:00:00 GMT" "2016-04-24 17:00:00 GMT"
[7] "2016-04-24 18:00:00 GMT" "2016-04-24 19:00:00 GMT"
[9] "2016-04-24 20:00:00 GMT" "2016-04-24 21:00:00 GMT"

> scale_x_continuous(minor_breaks = basetime + (0:9)*3600)
<ScaleContinuousPosition>
Range:
Limits: 0 -- 1
>

However, I can't reproduce your error:

> basetime <- as.numeric(as.POSIXct("2016-04-24 12:00:00 CEST",origin =
"1582-10-14", tz = "GMT"))
scale_x_continuous(minor_breaks = as.POSIXct(basetime + (0:9)*3600,origin=
"1970-01-01",tz="GMT"))
> + <ScaleContinuousPosition>
Range:
Limits: 0 -- 1


Anyways, try just normal addition subtraction with POSIXt objects (in
seconds).

Good luck and please put your next question in form that makes it easier
for someone to help you. See: http://adv-r.had.co.nz/Reproducibility.html

Cheers
Brian

neuwirthe

unread,
Apr 26, 2016, 2:03:13 PM4/26/16
to ggplot2, erich.n...@univie.ac.at
library(dplyr)
library
(ggplot2)

basetime
<- as.POSIXct("2016-04-24 12:00:00 CEST",origin ="1582-10-14", tz = "GMT")

timevar
<- basetime + (0:9)*3600
mydf
<- data.frame(time=timevar,val=(1:10)^2)
mydf
%>%
  ggplot
(aes(x=time,y=val)) +
  geom_line
() +
  scale_x_continuous
(minor_breaks = timevar)


This produces the error.
Removing the last line and the + one the line above make the code work.

Brian

unread,
Apr 26, 2016, 2:14:04 PM4/26/16
to neuwirthe, ggplot2
Hi Erich,

try:

library(dplyr)
library(ggplot2)
basetime <- as.POSIXct("2016-04-24 12:00:00 CEST",origin ="1582-10-14", tz =
"GMT")
timevar <- basetime + (0:9)*3600
mydf <- data.frame(time=timevar,val=(1:10)^2)
mydf %>%
ggplot(aes(x=time,y=val)) +
## scale_x_continuous(minor_breaks = time) +
scale_x_datetime(minor_breaks = timevar) +
geom_line()

Thank you for providing nice code.

Cheers,
Brianm
Reply all
Reply to author
Forward
0 new messages