在闪亮的应用程序中添加颜色过滤器

时间:2018-01-01 12:15:24

标签: r ggplot2 shiny

我有以下闪亮的应用程序使用titanic_train数据集(库(titanic))

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

#Label as factors
titanic_train$Survived <- as.factor(titanic_train$Survived)
titanic_train$Pclass <- as.factor(titanic_train$Pclass)
#Check of ze een title hebben
titanic_train$Man <- ifelse(titanic_train$Embarked %in% c("S"), 1, 0)

setwd("")

UI <- fluidPage(
  titlePanel("Visualizing results of the titanic: "),
  sidebarLayout(
    sidebarPanel(
     selectInput("dataset", "Pick the dataset:",
                choices = unique(titanic_train$Man)),
     selectInput("dimension", "Pick the x-axis:",
                choices = c("Sex", "Pclass"))
    ),
    mainPanel(
      plotOutput("plot")
    ),
 )
)

Server <- function(input, output) {

  filtered_titanic <- reactive({
    titanic_train %>%
      filter(Man == input$dataset)
  })


  output$plot <- renderPlot({
    ggplot(filtered_titanic(), aes_string(x="Age", y=input$dimension, colour = "Survived")) + 
      geom_point()
  })
}

shinyApp(ui = UI, server = Server)

这样可行但我实际想做的是用彩色滤镜显示整个数据集,如:

ggplot(filtered_titanic(), aes_string(x="Age", y=input$dimension)) + 
          geom_point()

然后当我在输入框中选择一个值(输入$ choices)时,在其上放置一个颜色过滤器。因此,当我选择:&#34; Survived&#34;该功能应该成为:

ggplot(filtered_titanic(), aes_string(x="Age", y=input$dimension, colour="Survived")) + 
          geom_point()

所以基本上我应该在过滤器框中有三个选项 - &gt;

  • 没有任何过滤器的情节
  • 使用过滤器绘图 - 幸存
  • 使用过滤器绘图 - Pclass

我尝试添加&#34;&#34;对输入的测量,但我仍然看到颜色突然出现。有关如何将此作为最佳实践的任何想法?

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,这可以做你想要的,或者可以帮助你朝着正确的方向前进。我添加了一个输入来确定要变色的变量,如果用户没有选择变量,我会添加if else作为颜色返回NULL

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

#Label as factors
titanic_train$Survived <- as.factor(titanic_train$Survived)
titanic_train$Pclass <- as.factor(titanic_train$Pclass)
#Check of ze een title hebben
titanic_train$Man <- ifelse(titanic_train$Embarked %in% c("S"), 1, 0)

setwd("")

UI <- fluidPage(
  titlePanel("Visualizing results of the titanic: "),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Pick the dataset:",
                  choices = unique(titanic_train$Man)),
      selectInput("dimension", "Pick the x-axis:",
                  choices = c("Sex", "Pclass")),
      selectInput("my_color", "Pick the colour:",
                  choices = c("None","Survived", "Pclass"))
    ),
    mainPanel(
      plotOutput("plot")
    ),
  )
)

Server <- function(input, output) {

  filtered_titanic <- reactive({
    titanic_train %>%
      filter(Man == input$dataset)
  })


  output$plot <- renderPlot({
    ggplot(filtered_titanic(), aes_string(x="Age", y=input$dimension, 
      colour = if (input$my_color!="None") input$my_color else NULL)) + 
      geom_point()
  })
}

shinyApp(ui = UI, server = Server)

enter image description here

希望这有帮助!