Search code examples
rshinyrcharts

Automatically resize rChart in shiny


How can I automatically resize an rChart plot in shiny? I would like to fit the plot to the screen of the user, like it is done for regular plots with renderPlot. Here's a minimal example:

#Server.R
require(rCharts)
shinyServer(function(input, output) {
  output$chart1 <- renderChart2({
    r1 <- rPlot(mpg ~ wt | am + vs, data = mtcars, type = "point", color = "gear")
    return(r1)
    })
  })


#ui.R.
require(rCharts)
options(RCHART_LIB = 'polycharts')
shinyUI(shinyUI(fluidPage(
titlePanel("title panel"),      
   sidebarLayout(
      sidebarPanel("sidebar panel"),
        mainPanel("main panel",
                   chartOutput("chart1", 'polycharts'))
      )
    )
 ))

I tried adding:

w <- session$clientData$output_chart1_width
r1$set(width = w)

but it does not work.


Solution

  • You were almost there: rChart's chartOutput doesn't pass its size, so the workaround is to use a plotOutput object to do this.

    Here is a solution that works for me:

    #server.R
    require(rCharts)
    shinyServer(function(input, output, session) {
      output$chart1 <- renderChart2({
        r1 <- rPlot(mpg ~ wt | am + vs, data = mtcars, type = "point", color = "gear")
        r1$set(width = session$clientData$output_plot1_width)
        return(r1)
      })
    })
    
    
    #ui.R
    require(rCharts)
    options(RCHART_LIB = 'polycharts')
    shinyUI(shinyUI(fluidPage(
      titlePanel("title panel"),      
      sidebarLayout(
        sidebarPanel("sidebar panel"),
        mainPanel("main panel",
                  plotOutput("plot1", height = "1px"),
                  chartOutput("chart1", 'polycharts')
                  )
      )
    )
    ))
    

    Note: here is another example I wrote with a nvd3 type chart: https://gist.github.com/nassimhaddad/3057e9ac687591fa5138