我想使用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")
但是我收到以下警告:
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
更新:我的示例太少了,我还需要能够显示负差异,因此这将是更好的数据:
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)
答案分为两个部分。
difftime
对象根据help("scale_x_time")
,ggplot2
支持三种日期/时间类:scale_*_date
用于日期(类Date
),scale_*_datetime
用于日期时间(class POSIXct
)和scale_*_time
用于时间(类hms
)。最后一个是我们在这里需要的。
类hms
是difftime
向量的自定义类。as.hms()
有一种方法difftime
。所以。difftime
可以ggplot2
通过强制类来绘制对象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)
请注意,也会显示负时差。
OP要求刻度线应以hh:mm
格式标记。显然,默认格式为hh:mm:ss
。可以通过指定一个函数来修改此函数,该函数将中断作为输入,并将标签作为输出返回给and函数的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)
该format_hm()
函数将截断:ss
默认格式的零件。此外,轴的标签也很好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句