简体   繁体   English

ggplot中的xlim与POSIXct日期

[英]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). 我试图限制具有时间数据(POSIXct格式)的图形的x轴范围。

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 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 limit.Date(c(...),“ x”)中的错误:length(lims)== 2不是TRUE

2 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 错误:输入无效:date_trans仅适用于Date类的对象

Help getting one or both of these options working would be appreciated. 帮助使这些选项之一或全部起作用将不胜感激。

I could get it to work with some fake data and replacing with scale_x_datetime . 我可以将其用于处理一些假数据并替换为scale_x_datetime

Edit: changed from date to POSIXct date-time. 编辑:从日期更改为POSIXct日期时间。

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM