首页 > 解决方案 > 使用 plotOutput 中的过滤器获取 Shiny 应用程序中的动态用户定义数据

问题描述

我在过滤 ggplot2 可视化数据时遇到了麻烦。我想使用过滤器并输入 f 值,例如使用

data %>%
filter(Col == Number) 
ggplot() 

根据数据集进行可定制的绘图

我使用此代码生成了一个 Shiny 应用程序,该应用程序能够让用户上传数据并可以交互地绘制它,但过滤器不起作用。

library(shiny)
library(tidyverse)


ui <- shinyUI(
  fluidPage(
    h1(' output'),
    h2('Graphics'),
    sidebarLayout(
      sidebarPanel(
        fileInput(inputId = 'file1', label = 'Upload your Data:', accept=c('text/csv', 
                                                                           'text/comma-separated-values,text/plain', 
                                                                           '.csv')),
        tags$hr(), 

        selectInput('xcol', "X variable:", "", selected = ""),
        selectInput('ycol', 'Y variable:', "", selected = ""), 
        selectInput('filter1', 'Filter:', "", selected = "", multiple = TRUE),
        selectInput('filter2', 'Filter Value',"",selected = "")
      ),

      mainPanel(

        plotOutput("plot")

      )
    )

  )

)

server <- shinyServer(function(session, input, output){


   data <- reactive({

       req(input$file1)
       inFile <- input$file1 
       df <- read_csv(inFile$datapath)#, header = T, sep=",")



       updateSelectInput(session, inputId = 'xcol', label = 'X variable:',
                         choices = names(df), selected = names(df))
       updateSelectInput(session, inputId = 'ycol', label = 'Y variable:',
                        choices = names(df), selected = names(df))
       updateSelectInput(session, inputId = 'filter1', label = 'Filter:',
                         choices = names(df), selected ="")
       observe({
       updateSelectInput(session, inputId = 'filter2', label = 'Filter value', choices =c(0:10))
       })  
       return(df)

   }) 

   output$plot <- renderPlot({
     F1 <- input$filter1
     F2 <- input$filter2

       data() %>% filter(F1==F2)%>% 
       ggplot(aes(x =data()[input$xcol],y= data()[input$ycol]))+ 
       geom_point()

})
        })




shinyApp(ui = ui, server = server) 

太感谢了

标签: rgraphicsshiny

解决方案


ggplot()就我个人而言,我不会在电话中做任何子集。您也不需要(实际上不应该)data()ggplot()调用中指定。这就是我可能会这样做的方式(尽管如果您不提供可重现的数据则很难测试):

x_var <- reactive(input$xcol)
y_var <- reactive(input$ycol)

data() %>%
    filter(F1 == F2) %>%
    ggplot(aes_string(x = x_var(), y = y_var())) +
    geom_point()

关于我的最后一点,请考虑以下内容之间的区别:

mtcars %>% filter(carb == 2) %>% ggplot(aes(x = carb, y = wt)) + geom_point()
# this works!
mtcars %>% filter(carb == 2) %>% ggplot(aes(x = mtcars$carb, y = mtcars$wt)) + geom_point()
# this doesn't

后者不起作用,因为它试图绘制mtcars$carb,而不是过滤后的 ( mtcars == 2) 向量。


推荐阅读