Search code examples
rmergeshinyrcharts

rCharts - combine two rCharts like gvisMerge


Is there anyway, that I can combine two rCharts, like gvisMerge(obj1, obj2). I realized the rCharts objects are functions. Is there any way to combine R functions. I am using a shiny application in which I want to render two rCharts.

 output$chart = renderChart({
 a <- rHighcharts:::Chart$new()
 a$title(text = "Report 1")
 a$xAxis(categories = as.character(df1$Date))
 a$yAxis(title = list(text = "Report 1"))

 a$data(x = df1$Date, y = df1$Val1, type = "line", name = "Values 1")
 a$data(x = df1$Date, y = df1$Val2, type = "column", name = "Values 2")
 a

 b <- rHighcharts:::Chart$new()
 b$title(text = "Report 2")
 b$xAxis(categories = as.character(df2$Week))
 b$yAxis(title = list(text = "Report 2"))

 b$data(x = df2$Week, y = df2$Val3, type = "line", name = "Values 3")
 b$data(x = df2$Week, y = df2$Val4, type = "column", name = "Values 4")
 b
 return(a,b) # Can we combine both and return
 })

In ui.R

output$mytabs = renderUI({
  tabs = tabsetPanel(
         tabPanel('Plots', h4("Plots"), chartOutput("chart"))
  })

Solution

  • If you are using Shiny, I would recommend using its layout functions to layout your page and then place the charts where you desire. Here is a minimal example (you will have to set the widths of the charts correctly to avoid overlap)

    library(shiny)
    library(rCharts)
    
    runApp(list(
      ui = fluidPage(
        title = 'Multiple rCharts',
        fluidRow(
          column(width = 5, chartOutput('chart1', 'polycharts')),
          column(width = 6, offset = 1, chartOutput('chart2', 'nvd3'))
        )
      ),
      server = function(input, output){
        output$chart1 <- renderChart2({
          rPlot(mpg ~ wt, data = mtcars, type = 'point')
        })
        output$chart2 <- renderChart2({
          nPlot(mpg ~ wt, data = mtcars, type = 'scatterChart')
        })
      }
    ))