【问题标题】:How can I filter certain data based on user input in bar chart?如何根据条形图中的用户输入过滤某些数据?
【发布时间】:2021-10-06 14:05:39
【问题描述】:

我有一个类似于以下内容的 CVS 文件:

Country Category Value
Canada A 3
Canada B 4
Canada C 5
USA A 3
USA C 2
Mexico B 5
Japan A 6
Japan B 3
Japan C 2

我想创建一个条形图,其中 X 轴为国家,Y 轴为值。我还希望有一个侧面板下拉过滤器,其中列出了类别,并且只显示与所选类别相对应的数据。因此,如果选择了 A 类别,则 Canada bare 的值将为 3。我在将过滤器应用于 X 和 Y 轴时遇到了很多麻烦。这是我目前所拥有的:

library(shiny)
library(ggplot2)
library(scales)
library(data.table)
library(plotly)
library(dplyr)

df=read.csv("name.cvs")

ui <- fluidPage(
   
    titlePanel("Title"),
    
    sidebarLayout(
        sidebarPanel(
            selectInput("Category", "Select Category", choices = df$Category)
        ),
        
        mainPanel(
            plotlyOutput("chart")
        )
    ) 
)

server <- function(input, output, session) {
    output$chart <- renderPlotly({
           
        p <- plot_ly(       
            x = df$Country,
            y = df$VALUE,
            name = "Important Data",
            type = "bar" ,          
        )            
    })
}

shinyApp(ui, server)

您可能会说我是 R Shiny 的新手,我真的在为这个项目苦苦挣扎。任何帮助将不胜感激!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以使用input$Category 引用下拉值,并使用基本R subsetdplyr::filter 进行简单过滤就足够了。

    library(shiny)
    library(plotly)
    
    ui <- fluidPage(
      
      titlePanel("Title"),
      
      sidebarLayout(
        sidebarPanel(
          selectInput("Category", "Select Category", choices = df$Category)
        ),
        
        mainPanel(
          plotlyOutput("chart")
        )
      ) 
    )
    
    server <- function(input, output, session) {
      output$chart <- renderPlotly({
        sub_df <- subset(df, Category == input$Category)
        p <- plot_ly(       
          x = sub_df$Country,
          y = sub_df$Value,
          name = "Important Data",
          type = "bar" ,          
        )            
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 非常感谢!创建子集时有没有办法添加多个过滤器?假设我有另一个名为 category2 的列,我想以此为基础进行过滤。类似于 sub_df
    • 是的,你可以使用sub_df &lt;- subset(df, Category == input$Category &amp; Category2 == input$Category2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2017-04-09
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多