'How to show only categories with values greater than 0 in R plotly?

I am trying to generate a plot in shiny app using reactive table. While generating pie plot the categories are showing as expected. But when I try to generate the barchart I am seeing labels for categories that I do not want to show which are categories with count 0. Currently I am seeing all the labels in xaxis for bar chart.

Below is the code I am using to generate the pie and bar graph. I am only choosing first 10 rows so I want to see the plot for 10 categories only. Pie chart is fine but the barchart is the issue.

  output$fig_pie <- renderPlotly({
    fig <- req(summarised_frame()[1:10]) %>% plot_ly(labels = ~concept_name, values = ~count) %>% add_pie(hole = 0.6)

  })
  

  output$fig_bar_plotly <- renderPlotly({
    req(summarised_frame())
    
    p <- summarised_frame()[1:10]
    
    fig <- plot_ly(p, x = ~concept_name, y = ~count, type = "bar")
    fig
  })

enter image description here

enter image description here

This is the table used for plotting



Solution 1:[1]

I was able to figure out the issue. The datatable I was using to reder the plot had the categories as factor so it retained the factor level even when I filtered/selected only 10 rows. Once I removed the factors for unused categories the barchart was fixed.

output$fig_bar_plotly <- renderPlotly({
req(summarised_frame())

p <- summarised_frame()[1:10]

p$concept_name <- droplevels(p$concept_name)

fig <- plot_ly(p, x = ~concept_name, y = ~count, type = "bar")
fig

})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 utsab shrestha