简体   繁体   中英

Shiny R histogram not changing with slider

I am trying to create an histogram using shiny on my dataset . I would like to be able to use a slider on it in order to change the number of histograms. My dataset has a column (cocoa percentage) with values in [50, 100]. After making it numeric instead of categorical, I would use the histogram to see the frequence of 50, 51, ... or the frequence of 50-55, 56-60, ... I wrote this code, but nothing happens when I run it. What am I doing wrong? Can you help me make it work please?


library(shiny)
library(shinythemes)
library(ggplot2)
library(plotly)
library(leaflet)
library(DT)

ui <- fluidPage(

    titlePanel("Chocolate Bar Ratings"),

        # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 1)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

server <- function(input, output) {

    output$distPlot <- renderPlot({
        # generate bins based on input$bins from ui.R
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        # draw the histogram with the specified number of bins
        hist(chocolate$CocoaPerc, xlab="Percentuale di cacao", main="Frequenza della percentuale
di cacao", col = c("chocolate", "chocolate3", "chocolate2", "chocolate4"))

    })
}

# Run the application 
shinyApp(ui = ui, server = server)

The reason is that input$bins was not used in the output$distPlot function see the # <--- comment. Note also that I just invented a random data set:

library(shiny)

chocolate <- data.frame(CocoaPerc=runif(100, min=0, max=99))

ui <- fluidPage(

  titlePanel("Chocolate Bar Ratings"),

  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 1)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

server <- function(input, output) {

  output$distPlot <- renderPlot({
    # draw the histogram with the specified number of bins
    hist(chocolate$CocoaPerc, 
         nclass = input$bins, # <---
         xlab="Percentuale di cacao", 
         main="Frequenza della percentuale di cacao", 
         col = c("chocolate", "chocolate3", "chocolate2", "chocolate4"))
  })
}

# Run the application 
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