【问题标题】:Shiny App filter df once for multiple plotsShiny App 过滤一次 df 用于多个绘图
【发布时间】:2021-05-07 00:11:39
【问题描述】:

我有一个闪亮的应用程序,它根据选定的过滤器生成多个图,对于服务器部分中的每个图,我根据选定的输入过滤器过滤数据:

output$plot_1 <- renderPlot({     
     df <- df %>% filter(df$filter == input$age)
     #plot code here
  })

output$plot_2 <- renderPlot({     
     df <- df %>% filter(df$filter == input$age)
     #plot code here
  })

我必须为所有绘图执行此操作(过滤 renderPLot 函数中的 df)。是否可以在 renderPlot 之外进行,以便过滤后的 df 可用于所有绘图?

【问题讨论】:

  • filtered_df % filter(filter == input$age)}),然后你可以在你的renderPlot函数中使用filtered_df()

标签: r shiny


【解决方案1】:

当然,我们可以将过滤后的数据存储在响应式中,这样我们就可以在多个地方使用它。使用反应式时请注意双括号,即df_filtered()

这是一个最小的工作示例,显示数据存储在反应式中并在两个图中使用。


library(shiny)
library(dplyr)

ui <- fluidPage(
  
    selectInput("mydropdown", "Select Species", choices = unique(iris$Species)),
    
    plotOutput("plot_1"),
    
    plotOutput("plot_2")
    
)

server <- function(input, output, session) {
    
    #Reactive
    df_filtered <- reactive({
        
        df <- filter(iris, Species == input$mydropdown)
        
        return(df)
        
    })
    
    #Plot 1
    output$plot_1 <- renderPlot({
        
        plot(df_filtered()$Petal.Length)
        
    })
    
    #Plot 2
    output$plot_2 <- renderPlot({
        
        plot(df_filtered()$Petal.Width)
        
    })
    
}

shinyApp(ui, server)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 2019-02-04
    • 2019-03-19
    • 2021-02-05
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2021-12-08
    相关资源
    最近更新 更多