tnt
tnt

Reputation: 1459

xlim in ggplot with POSIXct dates

I'm trying to limit the range of my x-axis for a graph that has temporal data (POSIXct format).

str(df.alltags_barn.path$ts.h)
 POSIXct[1:61558], format: "2018-07-04 22:48:08" "2018-07-04 22:48:46" "2018-07-04 23:05:17" ...

I've tried the following two approaches with different error messages

1

p <- ggplot(data = filter(df.alltags_barn.path, mfgID %in% c(52)), 
        aes(ts.h, recvLon))
p + geom_point() + geom_path() + theme_bw() + 
  facet_wrap(~mfgID, scales = "free", ncol = 4) + 
  xlim(as.Date(c("2018-08-13", "2018-08-20")), format="%d/%m/%Y") +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))

Error in limits.Date(c(...), "x") : length(lims) == 2 is not TRUE

2

p <- ggplot(data = filter(df.alltags_barn.path, mfgID %in% c(52)), 
        aes(ts.h, recvLon))
p + geom_point() + geom_path() + theme_bw() + 
  facet_wrap(~mfgID, scales = "free", ncol = 4) + 
scale_x_date(limits=as.Date(c("2018-08-13", "2018-08-20")), labels=date_format("%b-%Y")) +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))

Error: Invalid input: date_trans works with objects of class Date only

Help getting one or both of these options working would be appreciated.

Upvotes: 4

Views: 4418

Answers (1)

Jon Spring
Jon Spring

Reputation: 66915

I could get it to work with some fake data and replacing with scale_x_datetime.

Edit: changed from date to POSIXct date-time.

library(lubridate)
sample_data <- data.frame(dates = seq.POSIXt(from = ymd_h("2018-01-01 00"),
                                           to   = ymd_h("2019-01-31 23"),
                                           by   = dhours(10)),
                          data = rnorm(951),
                          mfgID = sample(LETTERS[1:2], 951, replace = T))


p <- ggplot(data = sample_data,
            aes(dates, data)) + 
  geom_point() + geom_path() + theme_bw() + 
  facet_wrap(~mfgID, scales = "free", ncol = 4) + 
  scale_x_datetime(limits = ymd_h(c("2018-08-13 00", "2018-08-20 23"))) +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))
p

enter image description here

Upvotes: 6

Related Questions