R闪亮帮助:带有2个以上滤镜的条形图

时间:2018-12-20 02:24:00

标签: r shiny geom-bar

我创建了一个基本的Shiny应用程序,该应用程序使用不同的过滤器将数字输出绘制为条形图。一个允许用户选择与该名称关联的“名称”和“类型”的过滤器。 “名称”过滤器已启用多选,“类型”过滤器未启用。一切工作都很好,除了我意识到我构造代码的方式不允许我绘制我想要的所有不同组合。

#----df creation
name<-c("a","a","b","b","c","c")
type<-c("red","blue","blue","green","green","orange")
number<-c(30,20,42,16,23,62)
cbind(name,type,number)->df
as.data.frame(df)->df
unique(df$name)->name
unique(df$type)->type

#----shiny app
library(shiny)
library(dplyr)
library(ggplot2)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "name",
        label = "Name Selection",
        choices = name,
        selected = "a",
        multiple = TRUE
      ),
      radioButtons(
        inputId = "type",
        label = "Type Select",
        choices = type,
        selected = "red"
      )
    ),
    mainPanel(
      plotOutput(
        outputId = "graph"
      )
    )
  )

)

server <- function(input, output) {

  output$graph <- renderPlot({

    filtered <- 
      df %>%
      filter(name == input$name) %>%
      filter(type == input$type)

    ggplot(filtered,aes(x=name,y=number)) + geom_bar(stat = "identity")

  })


 }

 shinyApp(ui = ui, server = server)

上面的代码使我可以选择多个名称和不同的类型,但是它的出现取决于顺序。例如,尝试选择“ a”,然后选择“ b”,然后选择“ blue”作为类型。没有图。现在,以相反的方式尝试相同的类型:“ b”,然后“ a”,“ blue”作为类型。产生所需的输出。知道这里发生了什么吗?谢谢大家。

1 个答案:

答案 0 :(得分:0)

由于使用的是单选,因此需要更改过滤器以使用%in%运算符:

检查两个向量之间的相等性会导致成对比较,并在必要时回收较短的向量。请注意以下警告,较短的向量不能很好地划分为较大的向量:

a <- c(2,1)
b <- c(1,2,3)

a == b # [1] FALSE FALSE FALSE
       # Warning message:
       # In a == b : longer object length is not a multiple of shorter 
       # object length

a %in% b # [1] TRUE TRUE

此外,尽管没错,但第5-8行中的对右分配(->)虽然很不错,但我肯定会皱眉,尽管我相信人们会捍卫它的使用。

我相信这可以满足您的需求

#----df creation
name<-c("a","a","b","b","c","c")
type<-c("red","blue","blue","green","green","orange")
number<-c(30,20,42,16,23,62)
cbind(name,type,number)->df
as.data.frame(df)->df
unique(df$name)->name
unique(df$type)->type

#----shiny app
library(shiny)
library(dplyr)
library(ggplot2)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput(
        inputId = "name",
        label = "Name Selection",
        choices = name,
        selected = "a",
        multiple = TRUE
      ),
      radioButtons(
        inputId = "type",
        label = "Type Select",
        choices = type,
        selected = "red"
      )
    ),
    mainPanel(
      plotOutput(
        outputId = "graph"
      )
    )
  )

)

server <- function(input, output) {

  output$graph <- renderPlot({

    filtered <- 
      df %>%
      filter(name %in% input$name) %>%
      filter(type == input$type)

    ggplot(filtered,aes(x=name,y=number)) + geom_bar(stat = "identity")

  })


}

shinyApp(ui = ui, server = server)