Problem in Drilldown using Plotly

I want to drill down sales data from category and then to subcategory.
While doing so, in the second level graph i.e., subcategory plot, Subcategories of other category are also n X axis.

Eg: If I click furniture in the category plot, in the next plot Subcategories of other category are also visible
Screenshots attached below.

library(shiny)
library(dplyr)
library(readr)
library(data.table)

sales<-read.csv("/Users/gowthamanramadoss/Desktop/sales1.csv")

categories <- unique(sales$category)

ui <- fluidPage(
  plotlyOutput("bar"),
  uiOutput("back")
)

server <- function(input, output, session) {
  
  selections <- reactiveVal()
  output$bar <- renderPlotly({
    nSelections <- length(selections())
    print(nSelections)
    if (nSelections == 0) {
      sales %>%
        group_by(category) %>%
        summarise(pop = sum(as.numeric(sales))) %>%
        plot_ly() %>%
        add_bars(x = ~category, y = ~pop)
    } else {
      sales %>%
        filter(category %in% selections()) %>%
        group_by(subcategory) %>%
        summarise(pop = sum(as.numeric(sales))) %>%
        plot_ly() %>%
        add_bars(x = ~subcategory, y = ~pop)
    }
  })
  
  observeEvent(event_data("plotly_click"), {
    new <- event_data("plotly_click")$x
    old <- selections()
    selections(c(old, new))
  })
 
 
    
    output$back <- renderUI({
      if (length(selections())) 
        actionButton("clear", "Back", icon("chevron-left"))
    })
    
    # clear the chosen category on back button press
    observeEvent(input$clear, selections(NULL))
  
  
}

Can someone help.

Can you share sales1.csv (this appears to be a slightly modified version of the sales data in the plotly for R book)? What happens if you use readr::read_csv() instead of read.csv()?

I have uploaded the file in the google drive.
Below is the link of the file.

Tried with readr::read_csv

It worked.
Thanks a lot.

Can u explain me how is it different from read.csv()?

The important difference here is that readr::read_csv() does stringsAsFactors = FALSE by default. With R 4.0 and beyond, read.csv() does the same. The reason it impacts the plotly graph is that plotly displays all factor levels (even if they have 0 counts).

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.