lubridate:如何将difftime转换为毫秒单位(并绘制它)?

时间:2017-01-11 19:18:12

标签: r datetime ggplot2 lubridate

考虑以下示例

time = c('2013-01-03 22:04:21.549', '2013-01-03 22:04:21.549', '2013-01-03 22:04:21.559', '2013-01-03 22:04:23.559' )
ref = c('2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20')
value = c(1,2,3,4)


data <- data_frame(time, ref, value)
data <-data %>%  mutate(time = ymd_hms(time),
                        ref = ymd_hms(ref),
                        difftime = time - ref)

# A tibble: 4 × 4
                 time                 ref value   difftime
               <dttm>              <dttm> <dbl>     <time>
1 2013-01-03 22:04:21 2013-01-03 22:04:20     1 1.549 secs
2 2013-01-03 22:04:21 2013-01-03 22:04:20     2 1.549 secs
3 2013-01-03 22:04:21 2013-01-03 22:04:20     3 1.559 secs
4 2013-01-03 22:04:23 2013-01-03 22:04:20     4 3.559 secs

我想获得valuedifftime的散点图,其中difftime的单位为毫秒

我不知道该怎么做。我能做的最好的事情如下:

ggplot(data, aes(x = value, y = difftime )) + geom_point() 

Don't know how to automatically pick scale for object of type difftime. Defaulting to continuous.

enter image description here

但保持秒表示。

有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用attributes函数修改difftime对象的单位:

time = c('2013-01-03 22:04:21.549', '2013-01-03 22:04:21.549', '2013-01-03 22:04:21.559', '2013-01-03 22:04:23.559' )
ref = c('2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20')
value = c(1,2,3,4)


library("dplyr")
library("ggplot2")
library("lubridate")

DF <- data.frame(time, ref, value)
DF <- DF %>%  mutate(time = ymd_hms(time),
                        ref = ymd_hms(ref),
                        delta_time_secs = time - ref)

attributes(DF$delta_time_secs)
#
#$units
#[1] "secs"
#
#$class
#[1] "difftime"

使用attributes更改单位:

DF <- DF %>%  mutate(delta_time_msecs = (time - ref)*1000)

attributes(DF$delta_time_msecs)$units="milliseconds"

attributes(DF$delta_time_msecs)
#$units
#[1] "milliseconds"
#
#$class
#[1] "difftime



DF
#                 time                 ref value delta_time_secs  delta_time_msecs
#1 2013-01-03 22:04:21 2013-01-03 22:04:20     1      1.549 secs 1549 milliseconds
#2 2013-01-03 22:04:21 2013-01-03 22:04:20     2      1.549 secs 1549 milliseconds
#3 2013-01-03 22:04:21 2013-01-03 22:04:20     3      1.559 secs 1559 milliseconds
#4 2013-01-03 22:04:23 2013-01-03 22:04:20     4      3.559 secs 3559 milliseconds



ggplot(DF, aes(x = value, y = as.numeric(delta_time_msecs))) + geom_point() + ylab("Time in milliseconds")  

enter image description here