簡體   English   中英

如何在ggplot2中將difftime格式化為hh:mm?

[英]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)

根據您的約束,您可以考慮將difftimes轉換為不同的日期時間,ggplot可以很好地處理該日期時間:

library(lubridate)
a_date_times <- floor_date(Sys.time(), "1 day") + a
b_date_times <- floor_date(Sys.time(), "1 day") + b
ggplot(data=NULL, aes(x=a_date_times, y=b_date_times)) + 
  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM