Shiny create new variable based on Numeric Input and plot SOLVED BY MYSELF

Viewed 222

UPDATE: I've found a mistake - I used plotOutput instead of plotlyOutput. All is fine now.

I want to build a Shiny dashboard that does something like that:

  • takes a dataset with a numeric variable value
  • uses Numeric Input widget to obtain a numeric value
  • creates new variable value2=value*number provided in the Numeric Input box
  • plots a bar chart

The sample code is below. It correctly places the Numeric Input box, but the chart does not appear (the box where the chart is supposed to be is completely empty). Why?

library(shiny)
library(shinydashboard)
library(ggplot2)
library(tidyverse)

specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(numericInput("multiplier", label = "Enter multiplier", value=2)),
      box(plotOutput("plot_multiplier", height = 250))
    )
    
  )
)

server <- function(input, output) {
  
  dat <- reactive({
    data %>% mutate(value2=value*input$multiplier) %>% 
      pivot_longer(starts_with("value"), names_to = "col", values_to = "val")
  })  
  
  output$plot_multiplier <-renderPlotly({
    ggplotly(ggplot(dat(), aes(fill=col, y=val, x=specie)) + 
               geom_bar(position="dodge", stat="identity"))
  })

}


shinyApp(ui, server)

When I do this manually, the chart is produced as expected:

# Example with multiplier = 2
ds <- data %>% mutate(value2=value*2) %>%
  pivot_longer(starts_with("value"), names_to = "col", values_to = "val")

ggplot(ds, aes(fill=col, y=val, x=specie)) +
  geom_bar(position="dodge", stat="identity")
1 Answers

Use plotlyOutput instead of plotOutput and add library(plotly)

library(shiny)
library(shinydashboard)
library(ggplot2)
library(plotly)
library(tidyverse)

specie <- c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )
condition <- rep(c("normal" , "stress" , "Nitrogen") , 4)
value <- abs(rnorm(12 , 0 , 15))
data <- data.frame(specie,condition,value)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(numericInput("multiplier", label = "Enter multiplier", value=2)),
      box(plotlyOutput("plot_multiplier", height = 250))
    )
    
  )
)

server <- function(input, output) {
  
  dat <- reactive({
    data %>% mutate(value2=value*input$multiplier) %>% 
      pivot_longer(starts_with("value"), names_to = "col", values_to = "val")
  })  
  
  output$plot_multiplier <-plotly::renderPlotly({
    plotly::ggplotly(ggplot(dat(), aes(fill=col, y=val, x=specie)) + 
               geom_bar(position="dodge", stat="identity"))
  })
  
}


shinyApp(ui, server)

enter image description here

Related