0

I'm trying to generate a bar chart with user inputs. I tried using ~ before the inputs but it doesn't work. What I'm seeing is a blank canvas with the axis labels.

enter image description here

Code

library(shiny)
library(plotly)

ui <- fluidPage(
  titlePanel(tags$h4("Bar Chart")),
  sidebarLayout(
  sidebarPanel(selectInput("input1", label = NULL, choices = names(mtcars)),
               selectInput("input2", label = NULL, choices = names(mtcars))),
  mainPanel(plotlyOutput("bar"))
)
)

server <- function(input, output, session) {
  
  
  output$bar <- renderPlotly(
    mtcars %>% 
      plot_ly(
        x = ~input$input1,
        y = ~input$input2,
        
        type = "bar"
      )
  )
  
}

shinyApp(ui, server)
writer_typer
  • 708
  • 7
  • 25

2 Answers2

1

You can use get() to convert your input variable to something that plotly can work with. In your case try this:

 output$bar <- renderPlotly(
     mtcars %>% 
         plot_ly(
             x = ~get(input$input1),
             y = ~get(input$input2),
             
             type = "bar"
         )
pascal
  • 1,036
  • 5
  • 15
1

Following this post a second option would be to make use of as.formula like so:

server <- function(input, output, session) {
  output$bar <- renderPlotly(
    mtcars %>% 
      plot_ly(
        x = as.formula(paste0('~', input$input1)),
        y = as.formula(paste0('~', input$input2)),
        
        type = "bar"
      )
  )
}
stefan
  • 90,330
  • 6
  • 25
  • 51