r - 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 问题,显然没有解决。
- R 版本 3.6.0
- 情节版本 4.9.2.1
- 闪亮版本 1.5.0
解决方案
不知道为什么,但是当您在调用isolate
中输入时它会按预期工作:plot_ly
val$plt2 = plot_ly(mtcars,
x = ~get(isolate(input$select_xvar)),
y = ~mpg)
然后,您可以从中删除isolate
和:actionButton
renderPlotly
output$plt2 <- renderPlotly(val$plt2)
推荐阅读
- react-native - React Native 应用程序中类似 Uber 的抽屉导航
- python - Python嵌套字典在内部比较值
- php - 如何从 Laravel 数据库中的 Products 表中查询卖家 ID
- php - PHP 生成一个从 0 到 36 的数字可能是公平的
- django - 突然我在端点上得到 502,其余工作正常
- python - 解析大型 excel 文件并将结果写回分隔文本文件
- vim - VIM 删除 - 多行
- java - Java - if-else 语句返回假阴性
- r - 需要帮助从 R 中的日期中删除时间模式
- spring - BCryptPasswordEncoder 在升级到 spring secrity 5 后不工作