【问题标题】:Is it possible to have a dynamic chart type in shiny? (Type of output changes based on input)是否可以有闪亮的动态图表类型? (输出类型根据输入而变化)
【发布时间】:2021-12-24 02:09:44
【问题描述】:

我希望图表出现在相同的位置 在用户界面中,但图表输出的类型取决于用户选择的内容。该示例不起作用,但可以解释我在寻找什么。

简单示例

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)

如果有可能,请告诉我

【问题讨论】:

    标签: r shiny plotly rendering shiny-reactivity


    【解决方案1】:

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

    我希望这有效!祝你好运!

    【讨论】:

    • 效果很好!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2017-05-21
    • 2020-07-02
    • 1970-01-01
    • 2022-06-15
    • 2016-12-09
    • 1970-01-01
    相关资源
    最近更新 更多