[英]How to format difftime as hh:mm in ggplot2?
我想使用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)
到目前為止,我最好的方法是:
library(ggplot2)
library(lubridate)
a= as.difftime(c(-60, -4*60), unit="mins")
b= as.difftime(c(-60, 2*60+47), unit="mins")
xbreaks = seq(ceiling(min(b)/60), floor(max(b)/60)) * 60
ybreaks = seq(ceiling(min(a)/60), floor(max(a)/60)) * 60
ggplot(data=NULL, aes(x=b, y=a)) + geom_point(shape=1) +
scale_x_continuous(labels = f, breaks = xbreaks) +
scale_y_continuous(labels = f, breaks = ybreaks)
f <- function(x){
t = seconds_to_period(abs(x)*60)
r = sprintf("% 2i:%02i", sign(x)*hour(t), minute(t))
return(r)
}
答案分為兩個部分。
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
。 可以通過指定一個函數來修改此函數,該函數將中斷作為輸入,並將標簽作為輸出返回到scale_x_time()
和scale_y_time()
函數的labels
參數:
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
部分。 此外,軸的標簽也很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.