Plotly R中的时间序列

时间:2018-09-27 10:08:08

标签: r ggplot2 plotly

所以,我有这个数据

test_data <- structure(list(
  time = c(29510, 29528.023023023, 29546.046046046, 
           29564.0690690691, 29582.0920920921, 29600.1151151151, 
           29618.1381381381, 29636.1611611612, 29654.1841841842, 
           29672.2072072072, 29690.2302302302, 29708.2532532533, 
           29726.2762762763, 29744.2992992993, 29762.3223223223, 
           29780.3453453453, 29798.3683683684, 29816.3913913914, 
           29834.4144144144, 29852.4374374374), 
  sum = c(0L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 5L, 7L, 9L, 9L, 15L, 
          17L, 18L, 18L, 18L, 18L, 21L)), 
  .Names = c("time", "sum"), 
  row.names = c(NA, 20L), 
  class = "data.frame")

时间是数字。

我可以使用ggplot2完美地绘制它:

ggplot(test_data) +
    geom_line(aes(x=time, y=sum)) + 
    scale_x_time()

但是当我尝试使用plot_ly时,时间错误地显示为数字而不是时间。与ggplot2的scale_x_time函数有什么相似之处吗?

plot_ly(test_data, x = ~time, y = ~sum, type = 'scatter', mode = 'lines')

1 个答案:

答案 0 :(得分:1)

该怎么做,整合@ Z.Lin的建议,并消除一天的必要性:

test_data$time <- as.POSIXct(test_data$time, origin = "1970-01-01")  # as date
test_data$time <- strftime(test_data$time,format="%H:%M:%S")         # remove the day
plot_ly(test_data, x = ~time, y = ~sum, type = 'scatter', mode = 'lines')