【问题标题】:Setting limits with scale_x_datetime and time data使用 scale_x_datetime 和时间数据设置限制
【发布时间】:2015-08-16 22:05:29
【问题描述】:

我想为仅包含时间(无日期)的时间序列数据图设置 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))

【问题讨论】:

    标签: r ggplot2 time-series


    【解决方案1】:

    错误消息说您应该在lims 上使用as.POSIXct。 您还需要在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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      相关资源
      最近更新 更多