【问题标题】:Shiny actionButton() output in onRender() function of htmlWidgetshtmlWidgets 的 onRender() 函数中的闪亮 actionButton() 输出
【发布时间】:2017-04-29 20:33:11
【问题描述】:

我的目标是创建一个脚本,最初显示一个空白的绘图。如果用户点击一个闪亮的动作按钮说“添加点”,那么点将通过 htmlWidgets 的 onRender() 函数添加到绘图图中。这会很有效,因为当用户选择 Shiny actionButton 时,不需要重新绘制背景空白绘图图。

但是,为了让我实现这一点,我需要找到一种方法将 Shiny actionButton 中的更改直接指示到 onRender() 函数中,以便空白绘图图(在下面的代码中称为“pP ") 根本不会改变。我在下面的 onRender() 代码中添加了两行注释作为 if 语句,以显示我的目标。

我知道有一个名为 Shiny.onInputChange('variable', variable) 的函数可以在 onRender() 函数内部调用以保存在 onRender() 内部创建的变量,以便可以像 Shiny 一样使用在 onRender() 函数之外输入。所以,我想我正在寻找相反的东西(将闪亮的输入值直接传输到 onRender() 函数)。

ui <- shinyUI(fluidPage(
  uiOutput("add"),
  plotlyOutput("myPlot", height = 700)
))

server <- shinyServer(function(input, output) {

  output$add <- renderUI({
    actionButton("addButton", "Add points")
  })

  output$myPlot <- renderPlotly({
    p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_blank()
    pP <- ggplotly(p)

    pP %>% onRender("
    function(el, x, data) {

//if (input$addButton selected){
      var Traces = [];
      var trace = {
      x: data.x,
      y: data.y,
      mode: 'markers',
      marker: {
      color: 'green',
      size: 6
      },
      hoverinfo: 'none'
      };
      Traces.push(trace);
      Plotly.addTraces(el.id, Traces);
//}
    }", data = list(x = mtcars$wt, y = mtcars$mpg))
  })      
})

shinyApp(ui, server)

注意:这类似于我之前提出的问题 (Using Shiny actionButton() function in onRender() function of htmlWidgets)。不过,我简化了这个问题,并希望确定是否有一个简单的答案可用。

【问题讨论】:

    标签: shiny plotly htmlwidgets onrender


    【解决方案1】:

    您可以尝试直接使用一些 jQuery 来响应用户单击按钮。 onRender 将是:

    function(el, x, data) {
      $('#addButton').on('click',function() {
        var Traces = [];
        var trace = {
          x: data.x,
          y: data.y,
          mode: 'markers',
          marker: {
            color: 'green',
            size: 6
          },
          hoverinfo: 'none'
        };
        Traces.push(trace);
        Plotly.addTraces(el.id, Traces);
      })
    }
    

    为此,需要先创建按钮,因此我将您的 ui.R 更改为:

    ui <- shinyUI(fluidPage(
      actionButton("addButton", "Add points"),
      plotlyOutput("myPlot", height = 700)
    ))
    

    编辑:如果你想保留renderUI,你可以使用事件委托将你的功能按钮绑定在#add div中:

    function(el, x, data) {
      $('#add').on('click','button',function() {
        var Traces = [];
        var trace = {
          x: data.x,
          y: data.y,
          mode: 'markers',
          marker: {
            color: 'green',
            size: 6
          },
          hoverinfo: 'none'
        };
        Traces.push(trace);
        Plotly.addTraces(el.id, Traces);
      })
    }
    

    【讨论】:

    • 非常有帮助 - 谢谢!在动态生成 Shiny UI 输入的情况下,我也希望解决这个问题。我针对该目标发布了一个类似的帖子 (stackoverflow.com/questions/43707379/…)。
    • 如果您想使用renderUI,我编辑了答案,如果可以,请随时删除其他问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    相关资源
    最近更新 更多