首页 > 解决方案 > 如何使用 R Shiny 中的单选按钮在同一图形上显示图?

问题描述

在这个闪亮的应用程序中,如果我们选择第二个单选按钮“在同一图上显示图”,我希望在同一图上显示两个图 提前谢谢您的帮助

library(shiny)
library(plotly)

ui <-fluidPage(
  titlePanel("title panel"),
  sidebarLayout(position = "left",
                sidebarPanel(
                  radioButtons(inputId = "plot", label=' ', choices=c("display plots on separate figures", "display plots on the same figure"))
                ),
                mainPanel(
                  plotlyOutput(outputId = "fbPlot1"),
                  plotlyOutput(outputId = "fbPlot2")
                )
                ))

server <- function(input, output) {
  output$fbPlot1 <- renderPlotly(
    fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
    
  )
  output$fbPlot2 <- renderPlotly(
    fig2 <- plot_ly(data = iris, x = ~Petal.Length, y = ~Sepal.Length,color ='blue')
    
  )
}

shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


通过使用 shinyjs 包,您可以根据事件隐藏/显示 UI 元素。

library(shiny)
library(plotly)
library(shinyjs)

ui <-fluidPage(
  titlePanel("title panel"),
  useShinyjs(),
  sidebarLayout(position = "left",
                sidebarPanel(
                  radioButtons(inputId = "plot", label=' ', choices=c("display plots on separate figures", "display plots on the same figure"))
                ),
                mainPanel(
                  div(id = "plot1", plotlyOutput(outputId = "fbPlot1")),
                  div(id = "plot2", plotlyOutput(outputId = "fbPlot2")),
                  div(id = "plot3", plotlyOutput(outputId = "fbPlot3"))
                )
  ))

server <- function(input, output) {
  
  rv <- reactiveValues()
  
  observe({
    rv$fig1 <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
    rv$fig2 <- plot_ly(data = iris, x = ~Petal.Length, y = ~Sepal.Length,color ='blue')
    rv$fig3 <- subplot( rv$fig1, rv$fig2)
  })
  
  output$fbPlot1 <- renderPlotly({
    rv$fig1
  })
  output$fbPlot2 <- renderPlotly({
    rv$fig2 
  })
  output$fbPlot3 <- renderPlotly({
    rv$fig3 
  })
  
  observeEvent(input$plot, {
    req(input$plot)
    
    print(input$plot)
    if(input$plot == "display plots on separate figures"){
      shinyjs::show("plot1")
      shinyjs::show("plot2")
      shinyjs::hide("plot3")
    }
    if(input$plot == "display plots on the same figure"){
      shinyjs::hide("plot1")
      shinyjs::hide("plot2")
      shinyjs::show("plot3")
    }
    
  }, ignoreNULL = FALSE)
}

shinyApp(ui = ui, server = server)

推荐阅读