在我的Shiny应用程序中,我使用了for循环来绘制不同的图,我希望用户能够单击每个图。我将如何实现这一目标,因为它目前只能进入最终剧情?
library(shiny)
server <- function(input, output, session) {
# data
v <- c(9,8,7,8,9,5,6,7,4,3)
w <- c(3,4,2,3,3,3,2,3,4,5)
x <- c(1,3,4,6,2,4,6,8,6,3)
y <- c(4,5,2,4,2,1,2,5,7,8)
z <- c(5,9,8,6,4,6,8,9,6,7)
df <- data.frame(v, w, x, y, z)
# initial plot that will allow user to change parameters (haven't implemented yet)
output$plot <- renderPlot(plot(df[[1]],df[[2]]))
# wait until the button is triggered
observeEvent(input$run, {
for (i in 5){
output$plot <- renderPlot(plot(df[[1]],df[[i]], main = i))
}
})
}
ui <- fluidPage(
actionButton("run", "Generate"),
plotOutput("plot")
)
shinyApp(ui = ui, server = server)
答案 0 :(得分:1)
您可以直接使用操作按钮的点击计数(即输入$ run)来代替for循环,下面的代码将逐一生成绘图,直到点击计数小于或等于5,然后返回到初始点击次数超过5时立即绘制。您可以根据自己的意愿修改else语句。
observeEvent(input$run, {
if(input$run <= 5){
output$plot <- renderPlot(plot(df[[1]],df[[input$run]], main = input$run))
}else output$plot <- renderPlot(plot(df[[1]],df[[2]]))
})
希望这会有所帮助
答案 1 :(得分:1)
您只需要使用将保持每次点击计数的变量:
library(shiny)
server <- function(input, output, session) {
# data
v <- c(9,8,7,8,9,5,6,7,4,3)
w <- c(3,4,2,3,3,3,2,3,4,5)
x <- c(1,3,4,6,2,4,6,8,6,3)
y <- c(4,5,2,4,2,1,2,5,7,8)
z <- c(5,9,8,6,4,6,8,9,6,7)
df <- data.frame(v, w, x, y, z)
# initial plot that will allow user to change parameters (haven't implemented yet)
output$plot <- renderPlot(plot(df[[1]],df[[2]]))
count<-0 # This is the counter which keeps track on button count
observeEvent(input$run, {
count <<- count + 1 # Increment the counter by 1 when button is click
if(count<6){
# Draw the plot if count is less than 6
output$plot <- renderPlot(plot(df[[1]],df[[count]],main = count))
}
else{
# Reset the counter if it is more than 5
count <- 0
}
})
}
ui <- fluidPage(
actionButton("run", "Generate"),
plotOutput("plot")
)
shinyApp(ui = ui, server = server)