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)
答案有两部分。
difftime
对象根据help("scale_x_time")
,ggplot2
支持三个日期/时间类:scale_*_date
日期 (class Date
)、scale_*_datetime
日期时间 ( class POSIXct
) 和scale_*_time
时间 (class hms
)。最后一个是我们这里需要的。
Classhms
是difftime
向量的自定义类。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
从默认格式截断部分。此外,轴被很好地标记。
归档时间: |
|
查看次数: |
1298 次 |
最近记录: |