我想要一个用于生成输出的Plot
按钮。这很好用。我遇到的麻烦是,当我更改输入时,我希望绘图变得无效,并停止显示。
预期行为:
- 应用加载
- 用户选择垃圾箱数量
- 用户点击绘图按钮
- 绘图已渲染
- 用户更改垃圾箱数量
- Shiny 删除了绘图,因为垃圾箱已更改
- 用户点击绘图按钮
- 绘图已渲染
实际行为:
- 应用加载
- 用户选择垃圾箱数量
- 用户点击绘图按钮
- 绘图已渲染
- 用户更改垃圾箱数量
- Shiny 什么都不做——保留陈旧的情节
- 用户点击绘图按钮
- 绘图已渲染
正如您在此屏幕截图中所看到的,bin 已设置为较小的值,并且 30 bin 直方图仍然显示:
在检查依赖关系图时,我注意到上面的第 5 步,input$bins
和 bindEvent
之间的关系变为灰色(参见图片),最终停止output$distPlot
来自无效和重新计算。
这是代表
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
actionButton('plot', 'Plot')
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
x = faithful[,2]
# Define server logic required to draw a histogram
server <- function(input, output) {
bins <- reactive({
seq(min(x), max(x), length.out = input$bins + 1)
}) %>%
bindEvent(input$plot)
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
# draw the histogram with the specified number of bins
hist(x, breaks = bins(), col = 'darkgray', border = 'white',
xlab = 'Waiting time to next eruption (in mins)',
main = 'Histogram of waiting times')
})
}
# Run the application
shinyApp(ui = ui, server = server)
最佳答案
可以使用reactiveVal
实现所需的行为:
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
actionButton('plot', 'Plot')
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
x = faithful[,2]
# Define server logic required to draw a histogram
server <- function(input, output, session) {
bins <- reactiveVal(NULL)
observeEvent(input$plot, {
bins(seq(min(x), max(x), length.out = input$bins + 1))
})
observeEvent(input$bins, {
bins(NULL)
})
output$distPlot <- renderPlot({
req(bins())
# draw the histogram with the specified number of bins
hist(x, breaks = bins(), col = 'darkgray', border = 'white',
xlab = 'Waiting time to next eruption (in mins)',
main = 'Histogram of waiting times')
})
}
# Run the application
shinyApp(ui = ui, server = server)
关于r - bindEvent 似乎消除了对输入的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74883642/