简体   繁体   中英

Define column values as input for reactive shiny plot

I want to start a shiny app for practice where a use can choose from a dropdown the values in the "cut" column from the diamonds dataset (from ggplot2).

My ui looks as following:

library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  # Application title
  titlePanel("Reactive Boxplot"),

  # Show a boxplot of the selected cut
  mainPanel(
    selectInput("column", label = h3("Column to plot"),
                choices = c("", diamonds$cut),
                selected = 1,
                width='55%',
                multiple = FALSE),
    plotOutput("diamondshist")
  )
)
)

I don't know how to define the input variables as the five distinct values in the "cut" column of diamonds dataset. Any input on this?

My server file looks like shared below. I assume I would also need to adapt the input data for the plot.

library(shiny)
library(ggplot2)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {

  compute_plot <- reactive({
    if (input$column != ""){
      ggplot(diamonds[, input$column])+
        labs(title = "From diamonds dataset")+
        geom_boxplot(aes(x = cut, y = price))+
        scale_y_reverse()
    }
  })


  output$diamondshist <- renderPlot({
    compute_plot();
  })

})

I assume this is what you are after:

  • pass the levels of diamonds$cut as input selection
  • subset the diamonds dataset to the selected cut
library(shiny)
library(ggplot2)

# Define UI for application that draws a histogram
ui=shinyUI(fluidPage(

    # Application title
    titlePanel("Reactive Boxplot"),

    # Show a boxplot of the selected cut
    mainPanel(
        selectInput("column", label = h3("Column to plot"),
                    choices = c("", levels(diamonds$cut)),
                    selected = NULL,
                    width='55%',
                    multiple = FALSE),
        plotOutput("diamondshist")
    )
)
)




# Define server logic required to draw a histogram
server=shinyServer(function(input, output) {

    compute_plot <- reactive({
        if (input$column != ""){
            ggplot(subset(diamonds, cut==input$column))+
                labs(title = "From diamonds dataset")+
                geom_boxplot(aes(x = cut, y = price))+
                scale_y_reverse()
        }
    })


    output$diamondshist <- renderPlot({
        compute_plot();
    })

})

shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM