在时间轴上设置休息间隔

Gre*_*reg 6 r ggplot2 lubridate

首先让我们创建一些示例数据。时间使用lubridate's存储,hm因为这似乎最合适。

library(tibble)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

(
  data <- tibble(
    Time = hm('09:00', '10:30'),
    Value = 1
  )
)
#> # A tibble: 2 x 2
#>   Time         Value
#>   <S4: Period> <dbl>
#> 1 9H 0M 0S         1
#> 2 10H 30M 0S       1
Run Code Online (Sandbox Code Playgroud)

这是我希望情节的样子。现在,我已经以半小时为间隔手动指定了休息时间。

library(ggplot2)
library(scales)

ggplot(data, aes(Time, Value)) +
  geom_point() +
  scale_x_time(breaks = hm('09:00', '09:30', '10:00', '10:30'))
Run Code Online (Sandbox Code Playgroud)

我想每隔半小时自动创建这些休息时间。尝试使用scales::date_breaks会出错。

ggplot(data, aes(Time, Value)) +
  geom_point() +
  scale_x_time(breaks = date_breaks('30 mins'))
#> Error in UseMethod("fullseq"): no applicable method for 'fullseq' applied to an object of class "c('hms', 'difftime')"
Run Code Online (Sandbox Code Playgroud)

尝试使用创建中断seq也会出错。

seq(hm('09:00'), hm('10:30'), hm('00:30'))
#> Note: method with signature 'Period#ANY' chosen for function '-',
#>  target signature 'Period#Period'.
#>  "ANY#Period" would also be valid
#> estimate only: convert to intervals for accuracy
#> Error in if (sum(values - trunc(values))) {: argument is not interpretable as logical
Run Code Online (Sandbox Code Playgroud)

小智 10

使用breaks_width()包中的新功能scales

ggplot(data, aes(Time, Value)) +
  geom_point() +
  scale_x_time(breaks = scales::breaks_width("30 min"))
Run Code Online (Sandbox Code Playgroud)


cam*_*lle 9

你得到的错误消息,处理方法applied to an object of class "c('hms', 'difftime')",应该给你一个线索,这里有一个类问题。首先要做的是检查您的时间类别,并检查文档 ( ?hm),这两者都会告诉您hm实际返回的是一个周期对象,而不是日期时间。

library(tidyverse)
library(lubridate)

class(data$Time)
#> [1] "Period"
#> attr(,"package")
#> [1] "lubridate"
Run Code Online (Sandbox Code Playgroud)

所以你需要Time变成一个Date或类似的对象。有不同的方法可以做到这一点,但我只是快速地将今天的日期粘贴Time在一起,然后转换为日期时间对象。如果您实际上不需要日期,我使用的日期并不重要;它基本上是创建您需要的对象的虚拟对象。

你也想要scale_x_datetime而不是scale_x_date。如果不设置date_labels参数,您将拥有像“ 2018-05-28 09:00:00”这样的标签,因此您可以通过向date_labels.

data %>%
  mutate(time2 = paste(today(), Time) %>% as_datetime()) %>%
  ggplot(aes(time2, Value)) +
  geom_point() +
  scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M")
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.2.0)于 2018 年 5 月 28 日创建。