情况是这样的:
我正在构建一个应用程序,在选择一些输入并单击操作按钮后填充图表。但是,我期望的行为是每次单击该按钮时,它都会覆盖旧图表。相反,我注意到即使在使用新输入单击按钮后它似乎仍保留这些值。
要重现这一点,请考虑下面的代码。如果选择所有值(A、B、C、D、E)并按计算,您将获得图表输出。但是,如果您随后清除输出并选择(A,C,E),您仍然会获得(B,D)的结果/行,即使在第二次单击操作中未选择它们。我想在每次单击时清除 df2() 数据框,并仅绘制当时选择的项目的图表。
非常感谢任何建议。
library(dplyr)
library(DT)
library(plotly)
library(shiny)
library(shinydashboard)
library(shinyWidgets)
################################################################################
## UI code
################################################################################
ui <- fluidPage(
# Select
################################################################################
sidebarLayout(
sidebarPanel(
# Selector
selectInput("input1",
label = h4("Choose an item"),
choices = c("A","B","C","D","E"),
multiple = TRUE,
selectize = TRUE),
# Action Buttons
fluidRow(
# Calculate
actionButton("calc", label = "Calculate")
)
),
mainPanel(
plotlyOutput("plot",height=400)
)
)
)
server <- function(input, output, session) {
df2 = reactiveVal(
data.frame(
symbol = character(0),
metric = numeric(0)
)
)
df3 = reactiveVal(
data.frame(
symbol = character(0),
metric = numeric(0)
)
)
observeEvent(input$calc, {
df1 = data.frame(symbol = input$input1)
# Create table for the time series plot
plot_tbl = cbind(
df1,data.frame(x=sample.int(100, length(input$input1)), y=sample.int(100, length(input$input1)))
)
df2(dplyr::bind_rows(df2(), plot_tbl))
})
output$plot = renderPlotly({
ggplotly(
ggplot(data = df2()) +
geom_line(aes(x, y, color = symbol), size = 1, alpha = .9)
)
})
}
shinyApp(ui = ui, server = server)
解决问题的一个选项是初始化或(重新初始化)
df2()
作为observeEvent
内的空数据框:
library(dplyr, warn = FALSE)
library(plotly)
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("input1",
label = h4("Choose an item"),
choices = c("A", "B", "C", "D", "E"),
multiple = TRUE,
selectize = TRUE
),
fluidRow(
actionButton("calc", label = "Calculate")
)
),
mainPanel(
plotlyOutput("plot", height = 400)
)
)
)
server <- function(input, output, session) {
df2 <- reactiveVal()
observeEvent(input$calc, {
# Re-Init df2
df2(
data.frame(
symbol = character(0),
metric = numeric(0)
)
)
plot_tbl <- data.frame(
symbol = input$input1,
x = sample.int(100, length(input$input1)),
y = sample.int(100, length(input$input1))
)
df2(dplyr::bind_rows(df2(), plot_tbl))
})
output$plot <- renderPlotly({
req(df2())
ggplotly(
ggplot(data = df2()) +
geom_point(aes(x, y, color = symbol), size = 1, alpha = .9)
)
})
}
shinyApp(ui = ui, server = server)