将 rangeslider R Shiny 连接到 plotly plot

Connect rangeslider R Shiny to plotly plot

所以一个 plotly plot 有一个嵌入式 rangeslider 但是我不喜欢它的外观。 R Shiny 中的 rangeslider 看起来更好更专业,但是我如何将两者联系起来?

假设您有一个包含一些值和日期范围的数据框,例如:

library(lubridate)

    df <- data.frame(
  "Date" = c(seq(ymd('2015-09-15'), ymd('2015-09-24'), by = "1 days")),
  "values" = c(3,6,5,3,5,6,7,7,4,2)
    )

情节代码

library(plotly)

    plot_df <- plot_ly(df) 

    plot_df  <- plot_df  %>%  add_lines(type = 'scatter', mode = "lines",
                                      x = ~Date, y = ~values)

代码闪亮

library(shiny)
library(shinydashboard)

  ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
      box(plotlyOutput("plotdf", height = 250)),
      
      box(
        title = "Controls",
        sliderInput("Date", "", min = df$Date[1], tail(df$Date, 1), value = tail(df$Date, 1)
        )
      )
    )
  )
)

server <- function(input, output) {
  output$plotdf<-renderPlotly({
    plot_df
  })
}

shinyApp(ui, server)

我们可以使用 dplyr::filter 并将其通过管道传输到 plot_ly()

    output$plotdf<-renderPlotly({
        filter(df, Date <= input$Date) %>% 
        plot_ly() %>%  
         add_lines(type = 'scatter', mode = "lines",
                                            x = ~Date, y = ~values)
    })

编辑:下面是从应用程序中分离出来的情节代码,日期范围为 sliderInput 到 select。

library(shiny)
library(dplyr)
library(lubridate)
library(plotly)

source(file = 'my_functions_script.R', local = TRUE)


df <- data.frame(
    "Date" = c(seq(ymd('2015-09-15'), ymd('2015-09-24'), by = "1 days")),
    "values" = c(3,6,5,3,5,6,7,7,4,2)
)


library(shiny)
library(shinydashboard)

ui <- dashboardPage(
    dashboardHeader(title = "Basic dashboard"),
    dashboardSidebar(),
    dashboardBody(
        # Boxes need to be put in a row (or column)
        fluidRow(
            box(plotlyOutput("plotdf", height = 250)),
            
            box(
                title = "Controls",
                shiny::sliderInput("Date", "", min = df$Date[1], tail(df$Date, 1), value = c(df$Date[1],tail(df$Date, 1))
                )
            )
        )
    )
)

server <- function(input, output) {
    output$plotdf<-renderPlotly({
        filter(df,Date >= input$Date[[1]], Date <= input$Date[[2]]) %>% 
            plt()
        
    })
}

shinyApp(ui, server)