Using percent width for Rcharts

 ̄綄美尐妖づ 提交于 2020-01-04 14:11:05

问题


I was wondering how to set the width of an rChart using % as opposed to px. I noticed in the source code that it defaults to pixels. I'm trying to use it in a shiny app, and fixed with charts seem to be an issue as they don't scale with the rest of the user interface. Is there a way around this?


回答1:


This should be considered a hack, since neither rCharts or most of the libraries have built in responsive behavior. However, one change would be to define your own renderChart function with this behavior. Something like this might work if you define in the server piece of shiny.

renderChart_pct <- function(expr, env = parent.frame(), quoted = FALSE) {
  func <- shiny::exprToFunction(expr, env, quoted)
  function() {
    rChart_ <- func()
    cht_style <- sprintf("<style>.rChart {width: %s; height: %s} </style>",
                         #### change these here to desired %
                         "100%", "100%")
    cht <- paste(capture.output(rChart_$print()), collapse = '\n')
    HTML(paste(c(cht_style, cht), collapse = '\n'))
  }
}

Then use renderChart_pct instead of renderChart2. You'll probably notice that the result will not be truly responsive. Altogether, here would be an example with dPlot.

  library(shiny)
  library(rCharts)

  renderChart_pct <- function(expr, env = parent.frame(), quoted = FALSE) {
    func <- shiny::exprToFunction(expr, env, quoted)
    function() {
      rChart_ <- func()
      cht_style <- sprintf("<style>.rChart {width: %s; height: %s} </style>",
                           "100%", "100%")
      cht <- paste(capture.output(rChart_$print()), collapse = '\n')
      HTML(paste(c(cht_style, cht), collapse = '\n'))
    }
  }

  ui = shinyUI(fluidPage(
    fluidRow(
      column(4,
        h1("Filler Header") 
      )
      ,column(8,
        div (
          showOutput("myChart", "dimple")
        )
      )
    )
  ))

  server = function(input,output){
    output$myChart <- renderChart_pct({
      d = dPlot(
        x~x
        , data = data.frame(x=1:10)
        , type = "line"
        , height = 500
        , width = NULL
      )
    })
  }

  runApp( list(ui=ui,server=server))


来源:https://stackoverflow.com/questions/28134392/using-percent-width-for-rcharts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!