RCharts + Shiny动态更改图表数据

时间:2015-10-17 00:55:46

标签: r shiny rcharts

这是我第一次使用rcharts和闪亮的。我正在尝试创建一个基本的闪亮应用程序,用户可以从下拉菜单中选择股票,并在rcharts图表中比较他们的表现(我想使用rcharts进行交互)。

我设法创建了下拉菜单和rcharts图表,但无法获取创建图表的数据进行更改。代码如下:

ui.R

    shinyUI(fluidPage(
  titlePanel("S&P 500 Retroactive Stock Comparision - 2009 and 2010"),
  sidebarLayout(
    sidebarPanel(uiOutput("stockA"), uiOutput("stockB"),submitButton("Submit")),
    mainPanel(showOutput("StockPlot","NVD3"))
  )
))

server.R:

stock.names<-reactive({
  ## data from :  http://pages.swcp.com/stocks/#historical%20data 
  stocks_data<-read.table("S.P.500_data.txt",sep=",")
  colnames(stocks_data)<-c("Date","Ticker","Open","High","Low","Close","Volume") 
  stocks_data$Date<- as.Date(as.character(stocks_data$Date), "%Y%m%d")

  stocks_data$Percent.Change<-((stocks_data$High-stocks_data$Low)/stocks_data$Open)*100

  #get company names + match with ticker symbols
  library(RCurl)
  company_names1 <- "http://data.okfn.org/data/core/s-and-p-500-companies/r/constituents.csv"
  company_names2<-getURL(company_names1)
  company_names3<-read.csv(textConnection(company_names2))

  stocks_data$Company.Names<-company_names3[match(stocks_data$Ticker,company_names3$Symbol),"Name"]

  x<-sort(unique(as.character(stocks_data$Company.Names)))
  return(x)
})

library(rCharts)


shinyServer(function(input,output){
  ########
  output$stockA <- renderUI({ 
    selectInput("stockA", "Select your first stock to compare:",choices=stock.names() )
  })
  ##########
  output$stockB <- renderUI({ 
    selectInput("stockB", "Select your second stock to compare:",choices=stock.names() )
  })

  ########
stockA.name<- reactive({
  input$StockA
}) 
  #########
stockB.name<- reactive({
  input$StockB
})

#######

chart.data<-reactive({
  data<-subset(stocks_data, Company.Names %in% input$stockA | Company.Names %in% input$stockB)
 return(data)
})
  ####### 
  output$StockPlot<-renderChart2({
    plot1<-nPlot(Close~Date,data=chart.data() ,group='Company.Names',type='lineChart')
    return(plot1)
  })
}
)

1 个答案:

答案 0 :(得分:0)

尝试将会话添加到您的服务器args,然后您应该可以使用

observeEvent(input $Submit, {

  stockA.name <- input$StockA
  stockB.name <- input$StockB

  chart.data <- subset(stocks_data, Company.Names %in% input$stockA | 
                                    Company.Names %in% input$stockB)

  output$StockPlot<-renderChart2({
    plot1 <- nPlot(Close~Date,data=chart.data(), 
                   group='Company.Names',type='lineChart')
    return(plot1)
  })

})

通过我的手机免费提供此功能,但如果它无法正常工作,我会稍后回来