在绘图中添加线性趋势线

时间:2018-09-07 14:28:05

标签: r plotly

我有一个时间序列数据,日期(x)和现金值(y)的图。如何在我拥有的每个当前图上添加线性趋势线

 x <- c("2016-01-31", "2016-02-28", "2016-03-31", "2016-04-30")
 as.Date(x,"%m/%d/%y")

 y_a <- c(100,200,90,250)
 y_b <- c(200,300,250,500)

 data <- data.frame(x, y_a, y_b)

 p <- plot_ly(data, x = ~x) %>%
   add_trace(y= ~y_a,type = 'scatter', mode = 'lines') %>%
   add_trace(y= ~y_b,type = 'scatter', mode = 'lines')
 p

1 个答案:

答案 0 :(得分:0)

您是否正在寻找类似的东西?

xx <- c(1,2,3,4)
fit <- lm(y_a ~ xx)
fit2 <- lm(y_b ~ xx)

plot_ly(data, x = ~x) %>%
  add_trace(y= ~y_a,type = 'scatter', mode = 'lines', color = I("Blue")) %>%
  add_trace(y= ~y_b,type = 'scatter', mode = 'lines', color = I("Red")) %>% 
  add_lines(y = fitted(fit), mode = "lines", color = I("Blue")) %>% 
  add_lines(y = fitted(fit2), mode = "lines", color = I("Red"))

enter image description here