设置时间轴上的休息时间间隔

Set interval between breaks on time axis

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

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

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

library(ggplot2)
library(scales)

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

我想每隔半小时自动创建这些休息时间。尝试使用 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')"

尝试使用 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

一种方法是将您的 Period 对象转换为 POSIXct,这样您就可以使用 scale_x_datetimedate_breaks 参数,例如

data %>%
  mutate(Time = as.POSIXct(Time, origin = "2018-01-01", tz = "GMT")) %>%
  ggplot(aes(Time, Value)) +
  geom_point() +
  scale_x_datetime(date_breaks = "30 min", date_labels = "%H:%M")

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

library(tidyverse)
library(lubridate)

class(data$Time)
#> [1] "Period"
#> attr(,"package")
#> [1] "lubridate"

因此您需要将 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")

reprex package (v0.2.0) 创建于 2018-05-28。

使用包 scales 中的新 breaks_width() 函数。

ggplot(data, aes(Time, Value)) +
  geom_point() +
  scale_x_time(breaks = scales::breaks_width("30 min"))