首页 > 解决方案 > R 闪亮的情节:无效仍然发生在隔离和观察事件中

问题描述

考虑一个简单的散点图,该散点图取决于用户选择(通过selectInput),该用户选择要在特定轴上绘制的变量。我们希望通过单击按钮来更新绘图,而不是在用户与selectInput. 因此,我们将 plot-update 逻辑包装在observeEvent依赖于按钮的 an 中。observeEvent更新reactiveValues包含绘图的对象。(这个例子之所以使用reactiveValues,是因为我们用 ggplot 和 plotly 图来证明这一点。)

运行应用程序时,在单击 之前actionButton,更改所选变量 fromselectInput不会更新绘图(如预期的那样)。但是,在actionButton单击一次之后,对 的任何进一步更改selectInput都会立即使情节图无效并导致它重新渲染。ggplot 图不会发生此行为(仅在actionButton单击 时更新)。

我还尝试将定义情节图的反应值包装在 中isolate,并创建对按钮的显式依赖input$update_plts,但这没有区别。

library(shiny)
library(ggplot2)
library(plotly)

ui <- {
    fluidPage(
        selectInput('select_xvar', label = 'select x var', choices = names(mtcars)),
        actionButton('update_plts', 'Update plots'),
        plotOutput('plt1'),
        plotlyOutput('plt2')
    )
}

server <- function(input, output, session) {
    
    val <- reactiveValues(
        plt1 = ggplot(mtcars) +
            geom_point(aes(x = wt, y = mpg)
        ),
        plt2 = plot_ly(mtcars,
            x = ~wt,
            y = ~mpg
        )
    )
    
    observeEvent(input$update_plts, {
        val$plt1 = ggplot(mtcars) +
            geom_point(aes_string(
                x = input$select_xvar,
                y = 'mpg'
            ))
        val$plt2 = plot_ly(mtcars,
            x = ~get(input$select_xvar),
            y = ~mpg)
    })
    
    output$plt1 <- renderPlot(val$plt1)

    # initial attempt with no isolate
    # output$pl2 <- renderPlotly(val$plt2)

    # second attempt with isolate, still invalidates instantaneously
    output$plt2 <- renderPlotly({
        input$update_plts
        isolate(val$plt2)
    })
}

shinyApp(ui, server)

任何想法为什么会出现这种情况?我能找到的唯一参考是一个封闭的 Github 问题,显然没有解决。

标签: rshinyr-plotly

解决方案


不知道为什么,但是当您在调用isolate中输入时它会按预期工作:plot_ly

val$plt2 = plot_ly(mtcars,
                   x = ~get(isolate(input$select_xvar)),
                   y = ~mpg)

然后,您可以从中删除isolate和:actionButtonrenderPlotly

output$plt2 <- renderPlotly(val$plt2)

推荐阅读