使用scale_x_datetime和时间数据设置限制 [英] Setting limits with scale_x_datetime and time data

查看:359
本文介绍了使用scale_x_datetime和时间数据设置限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为仅包含时间(无日期)的时间序列数据图设置x轴的边界.我的限制是:

I want to set bounds for the x-axis for a plot of time-series data which features only time (no dates). My limits are:

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

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

And my ggplot prints fine, but when I add this to scale_x_datetime

scale_x_datetime(limits = lims)

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

完全可复制的示例,由提供如何使用R创建时间散点图?

Fully reproducible example courtesy of 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))

推荐答案

错误消息指出您应该在lims上使用as.POSIXct. 您还需要在lims中添加日期(年,月和日),因为默认情况下将是`2015,这是不可行的.

the error message says that you should use as.POSIXct on lims. You also need to add the date (year, month and day) in lims, because by default it will be `2015, which is off limits.

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))

这篇关于使用scale_x_datetime和时间数据设置限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆