使用scale_x_datetime和时间数据设置限制

时间:2015-06-02 22:11:53

标签: r ggplot2 time-series

我想为x轴设置边界,以获得仅包含时间(无日期)的时间序列数据。我的极限是:

lims <- strptime(c("03:00","16:00"), format = "%H:%M")

我的ggplot打印正常,但是当我将其添加到scale_x_datetime

scale_x_datetime(limits = lims)

我得到Error: Invalid input: time_trans works with objects of class POSIXct only

How to create a time scatterplot with R?

提供完全可重现的示例
dates <- as.POSIXct(as.Date("2011/01/01") + sample(0:365, 100, replace=TRUE))
times <- as.POSIXct(runif(100, 0, 24*60*60), origin="2011/01/01")
df <- data.frame(
  dates = dates,
  times = times
)

lims <- strptime(c("04:00","16:00"), format = "%H:%M")

library(scales)
library(ggplot2)

ggplot(df, aes(x=dates, y=times)) + 
  geom_point() + 
  scale_y_datetime(limits = lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M")) + 
  theme(axis.text.x=element_text(angle=90))

1 个答案:

答案 0 :(得分:13)

错误消息表明您应在as.POSIXct上使用lims。 您还需要在lims中添加日期(年,月和日),因为默认情况下它将是2015年,这是不受限制的。

lims <- as.POSIXct(strptime(c("2011-01-01 03:00","2011-01-01 16:00"), format = "%Y-%m-%d %H:%M"))    
ggplot(df, aes(x=dates, y=times)) + 
    geom_point() + 
    scale_y_datetime(limits =lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M"))+ 
    theme(axis.text.x=element_text(angle=90))
相关问题