2017-06-02 103 views
-2

我想在一张图上有三个值。到目前为止,我可以有3行,如果我转换时间戳至今R在一张图中带有时间戳的多条线

MyData$Timestamp <- as.Date(MyData$Timestamp) 

,但我还想对我的图表小时。以下我的示例数据

  Timestamp Systolic.pressure Diastolic.pressure Pulse 
1 2017-06-01 23:35:31    125     80 70 
2 2017-06-02 23:35:43    130     90 89 
3 2017-06-02 23:35:43    135     93 96 
4 2017-06-03 23:35:56    140     90 98 

是否有任何方法来转换Timestamp做日期和时间?

+0

'?as.POSIXct'可能会有所帮助 – thelatemail

回答

1

您可以使用lubridate将时间戳转换为日期/时间。您还需要将数据帧从宽长格式转换而来,其中一列用于变量名称,另一列用于其值。 tidyr::gather可以做到这一点。

我不会把所有变量放在一张图上,因为血压测量的脉搏测量值有不同的单位。双Y轴是一个可能的但不推荐的解决方案。

我还想知道,在你的例子中,是否可以同时存在不同的值?考虑到数据的性质,我认为这不太可能。

所以这里有一个可能的解决方案,使用方面。我从这个图的示例数据中删除了第3行。

library(dplyr) 
library(tidyr) 
library(ggplot2) 
library(lubridate) 

MyData %>% 
    mutate(ts = ymd_hms(Timestamp)) %>% 
    # next line just drops row 3 
    slice(c(1:2, 4)) %>% 
    gather(var, val, -Timestamp, -ts) %>% 
    # reorder the variables for facets 
    mutate(var = factor(var, levels = c("Systolic.pressure", "Diastolic.pressure", "Pulse"))) %>% 
    ggplot(aes(ts, val)) + 
    geom_line() + 
    facet_grid(var ~ ., scales = "free") + 
    labs(x = "timestamp", y = "value") + 
    theme_light() 

enter image description here