【问题标题】:Using shiny to highlight specific bar in a bar chart使用闪亮突出条形图中的特定条形
【发布时间】:2018-01-01 21:17:29
【问题描述】:

我不确定我这样做是否正确(我愿意接受建议!)。但是,如果要创建一个闪亮的应用程序,我可以在其中选择一个条形图,然后该条形图应在图表中突出显示,我会尝试做什么。

对于这个例子,我使用了 titanic_train 数据集。

我愿意:

library(shiny)
library(ggplot2)
library(titanic)
library(dplyr)

UI <- fluidPage(

  # Application title
  titlePanel("Hello Shiny!"),

  sidebarLayout(
    sidebarPanel(
      selectInput("specific_bar", "Pick bar to highlight:",
                  choices = unique(titanic_train$Embarked))
    ),

    mainPanel(
      plotOutput("plot_nice")
    )
  )
)


Server <- function(input, output) {

  filtered <- reactive({
    titanic_train$Specific <- ifelse((titanic_train$Embarked == input$specific_bar), 1,0)
  })

  output$plot_nice <- renderPlot({
    ggplot(filtered(), aes_string(x="Embarked", y="Survived", fill = "Specific")) + 
      geom_bar(stat = "identity") 
  })


}

shinyApp(ui = UI, server = Server)

但是运行它会给我以下错误:

ggplot2 doesn't know how to deal with data of class numeric

而且问题似乎确实与 filters() 反应函数有关。对这里出了什么问题有任何想法吗?

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您必须在反应部分中要求返回 data.frame 对象,
    您所做的是返回一个向量,而不是将另一列添加到 titanic_train
    这应该可以解决它:

    library(shiny)
    library(ggplot2)
    library(titanic)
    library(dplyr)
    
    UI <- fluidPage(
    
      # Application title
      titlePanel("Hello Shiny!"),
    
      sidebarLayout(
        sidebarPanel(
          selectInput("specific_bar", "Pick bar to highlight:",
                      choices = unique(titanic_train$Embarked))
        ),
    
        mainPanel(
          plotOutput("plot_nice")
        )
      )
    )
    
    
    Server <- function(input, output) {
    
      filtered <- reactive({
        titanic_train$Specific <- ifelse((titanic_train$Embarked == input$specific_bar), 1,0)
        return(titanic_train)
      })
    
      output$plot_nice <- renderPlot({
        ggplot(filtered(), aes_string(x="Embarked", y="Survived", fill = "Specific")) + 
          geom_bar(stat = "identity") 
      })
    
    
    }
    
    shinyApp(ui = UI, server = Server)
    

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2016-03-25
      • 2014-04-04
      • 2020-10-05
      • 2019-09-25
      相关资源
      最近更新 更多