如何在 R Shiny 中向 ggplot 添加日期范围?

How to add a date range to ggplot in Rshiny?

我正在制作一个闪亮的应用程序来生成股票价格图。我想在给定特定日期范围的情况下生成绘图,但每当我尝试调整日期时都会收到错误“参数 1 不是向量”。如果我从我的应用程序中删除“daterangeinput”部分,一切正常。我附上了我的代码+数据。

运行下面的部分获取数据。

library(tidyquant)
library(tidyverse)
library(shiny)
library(shinyWidgets)
library(shinythemes)
library(plotly)

sp500_names <- tq_index("SP500") %>% 
  slice_head(n = 10) %>% 
  select(symbol, company)

tickers <- sp500_names[,1]

prices <- tq_get(tickers, 
                 get = "stock.prices",
                 from = today() - months(24),
                 to = today(), 
                 complete_cases = F) %>% 
    select(symbol, date, close)

闪亮应用代码:

ui <- fluidPage(
              
        # Title
        titlePanel("Stock Price Visualization and Forecasting"),
        
        # Sidebar
        sidebarLayout(
          sidebarPanel(width = 3,
                         pickerInput(
                         inputId = "stocks",
                         label = h4("Pick a stock"),
                         choices = tickers$symbol,
                         selected = tickers,
                         options = list(`actions-box` = TRUE),
                         multiple = T),
                       
                         # Date input
                         dateRangeInput("daterange", "Pick a Time Period",
                                  # value = today(),
                                  min = today() - months(23),
                                  max = today())),
                 
          # Plot results
          mainPanel(
            plotlyOutput("plot",height=600)
          )
        )
)



server <- function(input, output, session) {
          
            
            # Server logic based on user inputs
  
            observeEvent(input$stocks,{
              
              prices <- prices %>% 
                dplyr::filter(symbol %in% input$stocks) %>% 
                filter(date > input$daterange[1] & date <= input$daterange[2])
              
          # Create plot
  
  output$plot <- renderPlotly({
    print(
      ggplotly(prices %>% 
                 ggplot(aes(date, close, color = symbol)) + 
                 geom_line(size = 1, alpha = 0.9)+
                 theme_minimal(base_size=16) +
                 theme(axis.title=element_blank(),
                       plot.background = element_rect(fill = "white"),
                       panel.background = element_rect(fill="grey"),
                       panel.grid = element_blank(),
                       legend.text = element_text(colour="black"))
               )
             )
       })
  })   
}

shinyApp(ui, server)

问题是您没有为日期范围设置任何开始和结束日期,您的应用程序不会处理这个问题。因此,一个简单的解决方法是简单地设置一个默认的开始和结束日期。另外,恕我直言,我看不出 observeEvent 有任何理由。相反,我建议使用 reactive 来根据用户输入过滤数据,然后可以将其用于绘图:

library(tidyquant)
library(tidyverse)
library(shiny)
library(shinyWidgets)
library(shinythemes)
library(plotly)

ui <- fluidPage(
  # Title
  titlePanel("Stock Price Visualization and Forecasting"),
  # Sidebar
  sidebarLayout(
    sidebarPanel(
      width = 3,
      pickerInput(
        inputId = "stocks",
        label = h4("Pick a stock"),
        choices = tickers$symbol,
        selected = tickers,
        options = list(`actions-box` = TRUE),
        multiple = T
      ),
      # Date input
      dateRangeInput("daterange", "Pick a Time Period",
        # value = today(),
        start = min(prices$date),
        end = today(),
        min = min(prices$date),
        max = today()
      )
    ),
    # Plot results
    mainPanel(
      plotlyOutput("plot", height = 600)
    )
  )
)

server <- function(input, output, session) {
  prices_filtered <- reactive({
    req(input$stocks)
    prices %>%
      dplyr::filter(symbol %in% input$stocks) %>%
      filter(date > input$daterange[1] & date <= input$daterange[2])
  })
  
  output$plot <- renderPlotly({
    req(input$stocks)
    g <- ggplot(prices_filtered(), aes(date, close, color = symbol)) +
      geom_line(size = 1, alpha = 0.9) +
      theme_minimal(base_size = 16) +
      theme(
        axis.title = element_blank(),
        plot.background = element_rect(fill = "white"),
        panel.background = element_rect(fill = "grey"),
        panel.grid = element_blank(),
        legend.text = element_text(colour = "black")
      )
    ggplotly(g)
  })
}

shinyApp(ui, server)