Home > database >  Problem with Shiny and Plotly. Error in UseMethod
Problem with Shiny and Plotly. Error in UseMethod

Time:07-14

I am trying to render plotly based on the input selection. I am receiving an error: Warning: Error in UseMethod: no applicable method for 'layout' applied to an object of class "shiny.tag".

library(dplyr)
library(ggplot2)
library(shiny)
library(shinydashboard)
library(ggplot2)
library(plotly)
library(plotDK)

df <- tibble(postnr = c(4000, 2000,9000),
             kommunekoder = c(101, 147,153),
             reg_code = c(1,2,3),
             count = c(3,5,6))
  
ui <- shinyUI(fluidPage(
  box(plotlyOutput("map")),
  box(selectInput(
      "level",
      label= "Select map level:",
      choices = c("Zip code", "Municipality", "Region"),
      multiple = FALSE,
      selected = "Zip code"),
    solidHeader = TRUE,
    width = "5",
    height = "75px",
    status = "primary"
    )))

server <- shinyServer(function(input, output) {
    
plot <- reactive({ifelse(input$level == "Zip code", plotDK(plotlevel = "zipcode", value = "count", id ="postnr" , data = df, show_missing = TRUE),
                         ifelse(input$level == "Municipality", plotDK(plotlevel = "municipality", value = "count", id ="kommunekoder" , data = df, show_missing = TRUE),
                                plotDK(plotlevel = "region", value = "count", id ="reg_code" , data = df, show_missing = TRUE)))})

output$map <- renderPlotly({ggplotly(plot()   scale_fill_continuous(name ="Number of firms")) %>% layout(height = 500, width = 650)
})
  })
    shinyApp(ui = ui, server)

If I run the code in outside Shiny, it works:

plot <- plotDK(plotlevel = "region", value = "count", id ="reg_code" , data = df, show_missing = TRUE)
ggplotly(plot   scale_fill_continuous(name ="Number of firms")) %>% layout(height = 500, width = 650)

What am I missing?

CodePudding user response:

Would it be possible to change your Server function to:

server <- shinyServer(function(input, output) {
  output$map <- renderPlotly({
    if(input$level == "Zip code"){
      p <- plotDK(plotlevel = "zipcode", value = "count", id ="postnr" , 
             data = df, show_missing = TRUE)
    }
    if(input$level == "Municipality"){
      p <- plotDK(plotlevel = "municipality", value = "count", id ="kommunekoder" , 
             data = df, show_missing = TRUE)
    }
    if(input$level == "Region"){
      p <- plotDK(plotlevel = "region", value = "count", id ="reg_code" , 
             data = df, show_missing = TRUE)
    }
    ggplotly(p   scale_fill_continuous(name ="Number of firms")) %>% layout(height = 500, width = 650)
  })
})

This embeds the plotting function inside the map output. If you really need the plot to be stored in a reactive, then this won't work, but if you just need to make the plot so it can be rendered in the output, this should do the trick.

  • Related