我的目标是创建一个脚本,最初显示一个空白的绘图图。如果用户点击一个闪亮的动作按钮说“添加点”,那么点将通过 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)
注意:这类似于我之前提出的问题(在 htmlWidgets 的 onRender() 函数中使用 Shiny actionButton() 函数)。但是,我简化了问题,并希望确定是否有一个简单的答案可用。