Search code examples
rshinyrcharts

dynamically add rCharts to web page using shiny


I would like to generate multiple rCharts Pie Charts based on a selection of Group, this Group can change depending on the data frame. I would like to use similar example as in here

https://gist.github.com/wch/5436415/

someDF = structure(list(Variable.Type = c("Apple", "Orange", "Banana", 
"Apple", "Orange", "Banana"), Total = c(2, 1, 3, 6, 5, 4), Market = c("Pete", 
"Pete", "Pete", "Sams", "Sams", "Sams")), .Names = c("Variable.Type", 
"Total", "Market"), row.names = c(NA, -6L), class = "data.frame")

list = unique(someDF$Market)

In server.R

 output$somePieCharts = renderUI({
 list = unique(someDF$Group)
 plot_output_list = lapply(1:length(list), function(i){
   plotData = filter(someDF, Group==list[i])
   chartOutput(hPlot(Total~Variable.Type, data=plotData, type='pie'))
 }
                           )
 do.call(tagList, plot_output_list)
})

In ui.R

uiOutput('somePieCharts')

Solution

  • Here is how you can modify the dynamic plots example for use with hPlot. I have just replaced plotOutput with chartOutput and renderPlot with renderChart2. The rest of the changes are self-explanatory.

    library(shiny); library(rCharts)
    Markets = unique(someDF$Market)
    server = function(input, output) {
    
      # Insert the right number of plot output objects into the web page
      output$plots <- renderUI({
        plot_output_list <- lapply(1:2, function(i) {
          plotname <- paste("plot", i, sep="")
          chartOutput(plotname, "highcharts")
        })
    
        # Convert the list to a tagList - this is necessary for the list of items
        # to display properly.
        do.call(tagList, plot_output_list)
      })
    
      # Call renderPlot for each one. Plots are only actually generated when they
      # are visible on the web page.
      for (i in 1:length(Markets)) {
        # Need local so that each item gets its own number. Without it, the value
        # of i in the renderPlot() will be the same across all instances, because
        # of when the expression is evaluated.
        local({
          my_i <- i
          plotname <- paste("plot", my_i, sep="")
    
          output[[plotname]] <- renderChart2({
            print(my_i)
            plotData = subset(someDF, Market == Markets[my_i])
            print(plotData)
            hPlot(Total ~ Variable.Type, data = plotData, type='pie')
          })
        })
      }
    }
    
    ui = pageWithSidebar(
      headerPanel("Dynamic number of plots"),
    
      sidebarPanel(),
    
      mainPanel(
        # This is the dynamic UI for the plots
        uiOutput("plots")
      )
    )
    
    runApp(list(ui = ui, server = server))