代码之家  ›  专栏  ›  技术社区  ›  DTYK

闪亮-使用sliderInput中的日期范围输入用于ggplot的反应性dplyr表达式

  •  1
  • DTYK  · 技术社区  · 7 年前

    日期范围 供他们分析。前面关于SO的问题涉及使用 用于其滑块而不是范围(例如。 this post ). 因此,我无法复制解决方案。

    下面是我正在使用的软件包和模拟数据文件。有3列:(a)日期,(b)库存,(c)特定指标的值。

    library(shiny)
    library(readxl)
    library(dplyr)
    library(ggplot2)
    library(lubridate)
    
    df <- data.frame(Date = c("30/09/2018", "30/06/2018", "31/03/2018", "31/12/2017", "30/09/2017", "30/06/2017",
                          "31/03/2017", "30/09/2018", "30/06/2018", "31/03/2018", "31/12/2017", "30/09/2017", "30/06/2017",
                          "31/03/2017"),
                 Stock = c(rep("AAA", 7), rep("BBB", 7)),
                 Value = c(5.1, 5.2, 5.6, 5.5, 5.6, 5.7, 5.6, 6.4, 6.9, 6.7, 7.2, 7.2, 7.2, 7.7))
    
    df$Date <- as.Date(df$Date, format = "%d/%m/%Y")
    df$Stock <- as.character(df$Stock)
    

    以下是用户界面:

    # Define UI for application
    ui <- fluidPage(
    
      # Application title
      titlePanel("Stock Financials Trend"),
    
      # Sidebar with slider input to select date range
      sidebarLayout(
        sidebarPanel(
          selectInput("Stock_selector",
                      "Stock:",
                      c("AAA", "BBB")),
    
          # Add a Slider Input to select date range
          sliderInput("Date_range_selector", "Select Date Range",
                      min = 2017,
                      max = 2018,
                      value = c(2017, 2018))
        ),
    
        # Show a plot of the trend
        mainPanel(
          plotOutput("plot")
        )
      )
    )
    

    服务器如下所示:

    server <- function(input, output) {
    
      filtered_df <- reactive({
        df %>%
          filter(Stock == input$Stock_selector & year(Date) == between(year(Date), input$Date_range_selector[1], input$Date_range_selector[2]))
      })
    
      output$plot <- renderPlot({
        ggplot(filtered_df(), aes_string(x = "Date", y = "Value")) + geom_line() + geom_point() +
      labs(title = paste(input$Stock_selector, "Trend", sep = " "), y = "Value")
      })    
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    我的脚本显示,过滤是使用dplyr表达式完成的,然后将该表达式指定给反应式表达式,以便随后使用ggplot进行打印。

    numeric sliderInput year(as.Date("2017", format = "%d/%m/%Y")) 但输出仍然失败。

    预期输出如下所示(假设选择了股票AAA,范围设置为2018年至2018年):

    Expected output

    谢谢

    1 回复  |  直到 7 年前
        1
  •  7
  •   arg0naut91    7 年前

    您需要删除 year(Date) == 在筛选语句中,即将其更改为:

    filtered_df <- reactive({
        df %>%
          filter(Stock == input$Stock_selector & between(year(Date), input$Date_range_selector[1], input$Date_range_selector[2]))
      })