Shiny App使用quantmod绘制股票折线图报错求助
Fixing Your Quantmod Shiny Stock Chart Error
Let's break down the issues in your code and fix them step by step:
Key Problems in Your Original Code
- Shiny Output Binding Missing: You didn't wrap your plotting logic in
renderPlot()to connect it to thedistPlotoutput defined in your UI. Shiny requires this reactive wrapper to render plots dynamically based on user input. - Invalid
getSymbols()Parameter: Thetype="line"argument doesn't belong togetSymbols()— this function is only for fetching stock data, not specifying plot type. - Wrong Plotting Function: Using base R's
plot()with the xts object returned bygetSymbols()won't work as expected. Quantmod provideschartSeries(), which is purpose-built for its data structures and stock charting needs. - UI Syntax Error: The
selectedparameter inselectInput()was placed outside the function call, which breaks the UI setup.
Fixed Code
ui.R
library(shiny) shinyUI(fluidPage( titlePanel("Stock Chart"), sidebarLayout( sidebarPanel( # Fixed: Moved `selected` inside the selectInput argument list selectInput("stockInput", "Pick your stock:", choices = c("AMZN","FB","GOOG","NVDA","AAPL"), selected = "GOOG") ), mainPanel( plotOutput("distPlot") ) ) ))
server.R
library(quantmod) shinyServer(function(input, output){ # Fixed: Added renderPlot() to bind to the UI's distPlot output output$distPlot <- renderPlot({ # Fixed: Removed invalid `type` argument from getSymbols price <- getSymbols(input$stockInput, from='2019-01-01', # Added full date format to avoid parsing issues auto.assign = FALSE) # Fixed: Used quantmod's chartSeries instead of base plot chartSeries(price, main = paste("Stock Chart for", input$stockInput), theme = chartTheme('white')) }) })
Additional Notes
- I added a full date (
2019-01-01) to thefromargument to avoid potential date parsing inconsistencies. - Updated the plot title to be more descriptive by combining the selected stock ticker with static text.
chartSeries()handles the xts object fromgetSymbols()natively, so you'll get a proper quantmod-style stock chart with volume bars by default. You can customize this further (e.g., hide volume withshowVolume = FALSE) if needed.
内容的提问来源于stack exchange,提问作者Trungle83
相关产品推荐
相关产品推荐

