gpt4 book ai didi

R Shiny - 如何使用操作按钮在两个不同的绘图之间切换

转载 作者:行者123 更新时间:2023-12-04 09:24:28 25 4
gpt4 key购买 nike

在我的应用程序中,我希望默认显示 plot1,然后如果单击操作按钮,让 plot2 替换 plot1。如果再次单击,则恢复到 plot1,依此类推。


server <- function(input, output, session) {
plot1 <- (defined here)
plot2 <- (defined here)

which_graph <- reactive({
if (input$actionbutton == 1) return(plot1)
if (input$actionbutton == 2) return(plot2)
})

output$plot <- renderPlot({
which_graph()

})
}

最佳答案

您可以创建一个 reactiveValue 并使用 actioButton 来切换该值。例如

library(shiny)

ui <- fluidPage(
plotOutput("plot"),
actionButton("button", "Click")
)

server <- function(input, output, session) {
whichplot <- reactiveVal(TRUE)
plot1 <- ggplot(mtcars) + aes(mpg, cyl) + geom_point()
plot2 <- ggplot(mtcars) + aes(hp, disp) + geom_point()

observeEvent(input$button, {
whichplot(!whichplot())
})

which_graph <- reactive({
if (whichplot()) {
plot1
} else {
plot2
}
})

output$plot <- renderPlot({
which_graph()
})
}

shinyApp(ui, server)

此处 whichplot 以 TRUE 开始,然后每当您按下操作按钮时,它就会在 TRUE/FALSE 之间切换。这样你就不会改变 actionButton 的值;您只是在每次按下时更新状态。

如果你的绘图需要用户的任何输入,你也可以让它们响应

ui <- fluidPage(
selectInput("column", "Column", choices=names(mtcars)),
plotOutput("plot"),
actionButton("button", "Click")
)
server <- function(input, output, session) {
whichplot <- reactiveVal(TRUE)
plot1 <- reactive({ggplot(mtcars) + aes(mpg, .data[[input$column]]) + geom_point()})
plot2 <- reactive({ggplot(mtcars) + aes(.data[[input$column]], disp) + geom_point()})

observeEvent(input$button, {
whichplot(!whichplot())
})

which_graph <- reactive({
if (whichplot()) {
plot1()
} else {
plot2()
}
})

output$plot <- renderPlot({
which_graph()
})
}

关于R Shiny - 如何使用操作按钮在两个不同的绘图之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63044609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com