是否可以在闪亮中使用动态图表类型? (输出类型根据输入而变化)

Is it possible to have a dynamic chart type in shiny? (Type of output changes based on input)

我希望图表显示在 相同位置 UI 但图表输出的类型取决于用户选择什么。该示例不起作用,但可能会解释我在寻找什么。

简单示例

library(shiny)

# Define UI 
ui <- fluidPage(

    # Application title
    titlePanel("Title"),

    # Sidebar 
    sidebarLayout(
        sidebarPanel(
            selectInput("time", "Select time frame", choices = c("Hour", "Minute", "Day", "Month"), selected = "Day")
        ),

        # Show a plot of the generated distribution
        mainPanel(
           uiOutput("plot")
        )
    )
)

# Define server 
server <- function(input, output) {
    output$plot = renderUI({
        if(input$time %in% c("Hour", "Minute")){
            renderPlot(mtcars %>% ggplot(aes(disp, mpg )) + geom_point())
        }
        else if(input$time %in% c("Day", "Month")){
            renderPlotly(mtcars %>% ggplot(aes(disp, mpg )) + geom_point())
        }
    })
   
}

# Run the application 
shinyApp(ui = ui, server = server)

如果这样的事情可行,请告诉我

我认为这就足够了。您可以让 renderUI 有条件地切换 plotOutput,以便它显示在同一区域。使用您的大部分代码,我将 if 语句更改为具有 plot/plotly 输出而不是渲染 plot/plotly。然后,我为这些新绘图中的每一个都有一个单独的渲染 plot/plotly 输出,我将其标记为 plot1/2

library(shiny)
library(ggplot2)
library(plotly)

# Define UI 
ui <- fluidPage(
  
  # Application title
  titlePanel("Title"),
  
  # Sidebar 
  sidebarLayout(
    sidebarPanel(
      selectInput("time", "Select time frame", choices = c("Hour", "Minute", "Day", "Month"), selected = "Day")
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      uiOutput("plot")
    )
  )
)

# Define server 
server <- function(input, output) {
  
  output$plot = renderUI({
    if(input$time %in% c("Hour", "Minute")){
        plotOutput("plot1")
    } else if(input$time %in% c("Day", "Month")){
        plotlyOutput("plot2")
    }
  })
  
  output$plot1<-renderPlot({
    mtcars %>% ggplot(aes(disp, mpg )) + geom_point()
  })
  
  output$plot2<-renderPlotly({
    mtcars %>% ggplot(aes(disp, mpg )) + geom_point()
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

我希望这能奏效!祝你好运!