如何在 ggplot2 中将 difftime 格式化为 hh:mm?

pee*_*eer 2 r ggplot2 difftime

我想用 ggplot2 显示 difftime 数据,并且我希望刻度格式为hh:mm.

library(ggplot2)  

a= as.difftime(c("0:01", "4:00"), "%H:%M", unit="mins")
b= as.difftime(c('0:01', "2:47"), "%H:%M", unit="mins")

ggplot(data=NULL, aes(x=b, y=a)) + geom_point(shape=1) +    
                  scale_x_time(labels = date_format("%H:%M"), 
                               breaks = "1 hour")
Run Code Online (Sandbox Code Playgroud)

但我收到以下警告:

Don't know how to automatically pick scale for object of type difftime. Defaulting to continuous.
Warning message:
In structure(as.numeric(x), names = names(x)) : NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)

这是一个图表: 在此处输入图片说明

更新: 我的例子太小了,我还需要能够显示负差异,所以这将是更好的数据:

a= as.difftime(c(-60, -4*60),  unit="mins")
b= as.difftime(c(-60, 2*60+47), unit="mins")
ggplot(data=NULL, aes(x=b, y=a)) + geom_point(shape=1)
Run Code Online (Sandbox Code Playgroud)

Uwe*_*Uwe 5

答案有两部分。

绘制difftime对象

根据help("scale_x_time"),ggplot2支持三个日期/时间类:scale_*_date日期 (class Date)、scale_*_datetime日期时间 ( class POSIXct) 和scale_*_time时间 (class hms)。最后一个是我们这里需要的。

Classhmsdifftime向量的自定义类。as.hms()有一个方法difftime。所以。difftime可以ggplot2 通过强制转换为 class来绘制对象hms

a <- as.difftime(c(-60, -4 * 60),  unit = "mins")
b <- as.difftime(c(-60, 2 * 60 + 47), unit = "mins")
library(ggplot2)
ggplot(data = NULL, aes(x = hms::as.hms(b), y = hms::as.hms(a))) + 
  geom_point(shape = 1)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

请注意,还会显示负时差。

格式化刻度标签

OP 要求应以hh:mm格式标记刻度线。显然,默认格式是hh:mm:ss. 这可以通过指定一个函数来修改,该函数将中断作为输入并将标签作为输出返回给和函数的labels参数:scale_x_time()scale_y_time()

format_hm <- function(sec) stringr::str_sub(format(sec), end = -4L)
ggplot(data = NULL, aes(x = hms::as.hms(b), y = hms::as.hms(a))) + 
  geom_point(shape = 1) +
  scale_x_time(name = "b", labels = format_hm) +
  scale_y_time(name = "a", labels = format_hm)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

format_hm()函数:ss从默认格式截断部分。此外,轴被很好地标记。