如何使用 Plotly 在 R 中添加趋势线

How to add Trend Lines in R Using Plotly

我在 shiny 中有一个简单的应用程序,我想添加到趋势线中。我知道如何在 ggplot 中使用 lm 和 abline 函数添加线性趋势线,但如何在 R 中仅使用 Plotly 添加趋势线。

library(shiny)
library(plotly)
library(shinyWidgets)
set.seed(666)

df1 <- data.frame(Date = rep(seq(as.Date("2020-01-03"), by="day", len=12),10,replace = TRUE), 
                  Product = rep(LETTERS[1:10], each = 12), 
                  Value = sample(c(0:300),120, replace = T))


ui <- fluidPage(
  pickerInput("All", "Choose", multiple = F, choices = unique(df1$Product)                                          ,
              options = list(`max-options` = 4,size = 10)),
  plotlyOutput('plot')
  
)
server <- function(input, output) {
  
  trend<- reactive({
    df1 %>% 
      filter(Product %in% input$All) %>% 
      arrange(Date) %>% 
      droplevels()
  })
  output$plot <- renderPlotly({
    
    plot_ly(data=trend(), x=~Date,  y = ~Value,
            type = 'scatter', mode = 'lines+markers')
    
    
  })
  
}
shinyApp(ui = ui, server = server)

使用线性回归添加一条线如何?

library(shiny)
library(plotly)
library(shinyWidgets)
set.seed(666)

df1 <- data.frame(Date = rep(seq(as.Date("2020-01-03"), by="day", len=12),10,replace = TRUE), 
                  Product = rep(LETTERS[1:10], each = 12), 
                  Value = sample(c(0:300),120, replace = T))


ui <- fluidPage(
  pickerInput("All", "Choose", multiple = F, choices = unique(df1$Product)                                          ,
              options = list(`max-options` = 4,size = 10)),
  plotlyOutput('plot')
  
)
server <- function(input, output) {
  
  trend<- reactive({
    df1 %>% 
      filter(Product %in% input$All) %>% 
      arrange(Date) %>% 
      droplevels()
  })
  output$plot <- renderPlotly({
    t <- trend()
    m <- lm(Value~Date,data = t)
    p <-plot_ly(data=t, x=~Date,  y = ~Value,
            type = 'scatter', mode = 'lines+markers')
    p = add_lines(p, x=~Date, y=predict(m), name="Linear")
    
  })
  
}
shinyApp(ui = ui, server = server)