当x轴值为POSIXct时,R plotlly add_trace问题

时间:2017-07-03 05:01:55

标签: r ggplot2 plotly

我希望我们可以更轻松地在plotly中添加参考线,例如在geom_vline中使用geom_hlineggplot2甚至abline基地R.

我们可以使用add_trace函数来模仿geom_hline,但这次我似乎添加了错误的x值。

library(plotly)
library(lubridate)

D = data.frame(
  y = round(rnorm(10),1),
  x = structure(c(1498640394, 1498641854, 1498642201, 1498642515, 1498642749, 
            1498643011, 1498643247, 1498643499, 1498643735, 1498643992), 
            tzone = "UTC", class = c("POSIXct", "POSIXt"))
)

D$DATE_TIME = lubridate::ymd_hms(D$x)

MIN = min(D$x)

MAX = max(D$x)

H = 0

plot_ly(D, x = ~x, y = ~ y, type = "scatter", mode ="lines+markers") %>% 
  add_trace(x = c(MIN, MAX), y = c(H, H), name = "Reference", mode = "lines", line=list(color="red",dash="dash"))

我明白了 enter image description here

参考线路出错了。为什么会这样?

1 个答案:

答案 0 :(得分:0)

此问题的解决方法:

MIN = min(D$x) - 28800

MAX = max(D$x) - 28800

然后图表现在是正确的。

相关问题