Search code examples
rshinyplotlytrend

How to add Trend Lines in R Using Plotly


I have a simple application in shiny and I would like to add to the trend lines. I know how to add a linear trend line using the lm and abline functions in ggplot, but how do I add trend lines in R Using only Plotly.

enter image description here

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)


Solution

  • How about adding a line using linear regression?

    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)