ℕʘʘ*_*ḆḽḘ 5 datetime r 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
Run Code Online (Sandbox Code Playgroud)
我想获得的散点图value和difftime地方的单位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.
Run Code Online (Sandbox Code Playgroud)
但这保留了秒表示。
有任何想法吗?谢谢!!
You can use attributes function to modify the units of difftime object:
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"
Run Code Online (Sandbox Code Playgroud)
Using attributes to change units:
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2258 次 |
| 最近记录: |