Search code examples
rshinysubsetplotlyaction-button

When plotting a subset of my data with renderPlotly and plot_ly the values of the xAxis are not correct


I have values for different indicators for different countries. A stacked boxplot is supposed to visualize my data. My goal is that the user chooses with selectInput which countries should be plotted. Therefore I am using subset. The bars are only plotted for the chosen countries, but there are too many labels on the x Axis. It seems, that whenever a chosen country has a value of zero, all the labels are shown until a country has a value greater than zero.

To check whether the data is filtered correctly, I printed a table as well.

This is my code:

    Country <- c("Germany", "France", "UK", "Italy","Spain","US", "Canada","China","India","Japan")
data <- data.frame(country=Country,value=c(4,1,0,0,2,5,2,7,3,1,3,1,0,0,1,5,7,2,2,3),Ind=c(rep("1", times=10),rep("2", times=10)))



UI <- dashboardPage(

dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItemOutput("menu"),

      menuItem(selectInput(inputId = "ChooseCountry", label = "Choose Countries", Country,selected=list("India", "China"), multiple = T))
    )
  ),

  dashboardBody("barchart",
          fluidRow(
            box(plotlyOutput("step1"), width = 12),
          fluidRow(
            box(tableOutput("Table"), width=12)
          )

          ))

)




Server <- function(input, output, session) {



output$step1 <- renderPlotly({
  Data <- subset(data, country %in% input$ChooseCountry)
  plot_ly(data = Data, 
          x = ~country, y = ~value, color = ~Ind, type = "bar") %>%
    layout(barmode="stack")
})


output$Table <- renderTable( {
  Data <- subset(data, country %in% input$ChooseCountry)
})

}

Thank you for your suggestions! :)


Solution

  • You could drop the levels not used. Try this:

    Server <- function(input, output, session) {
      output$step1 <- renderPlotly({
        Data <- subset(data, country %in% input$ChooseCountry)
        Data[] <- lapply(Data, function(x) if(is.factor(x)) factor(x) else x)
        plot_ly(data = Data, 
                x = ~country, y = ~value, color = ~Ind, type = "bar") %>%
          layout(barmode="stack")
      })
      output$Table <- renderTable( {
        Data <- subset(data, country %in% input$ChooseCountry)
      })
    }
    
    shinyApp(ui = UI,server = Server)