Search code examples
rplotlybar-chart

Horizontal stacked bar chart using Plotly()


I'm trying to plot a horizontal stacked bar chart using plotly. But I'm getting the horizontal bar chart even when layout(barmode = 'stack') is specified with orientation = "h"

This is the data I need to plot as stacked chart

    Var1 Freq percentage
1 Tool 1  104         35
2 Tool 2   81         28
3 Tool 3   36         12
4 Tool 4   30         10
5 Tool 5   23          8
6 Tool 6   10          3
7 Tool 7    8          3
8 Tool 8    2          1

This is the code used to plot the chart using plotly

plot_ly(tooldf, x = tooldf$percentage,
        y = tooldf$Var1, 
        type = 'bar', orientation = "h",
        name = tooldf$Var1,
        text = paste(tooldf$percentage,"%"),
        textposition = 'top',
        hoverinfo = 'text',
        hovertext = paste('Tool: ', tooldf$Var1,
                          '<br> % of Usage: ', paste(tooldf$percentage,"%"))) %>%
  layout(barmode = 'stack')

Can anyone help me to plot a horizontal stacked chart in R?


Solution

  • You're missing another variable. Right now you're only passing through x and y axis, how do you want to stack it? I have introduced a new dummy variable called Type below.

    tooldf <- data.frame(Var1 = paste0("Tool", 1:8),
                         Freq = c(2, 8, 10, 23, 30, 36, 81, 104),
                         percentage = c(1, 3, 3, 8, 10, 12, 28, 35))
    
    tooldf <- tooldf %>%
                mutate(Type = Freq > mean(Freq))
    
    library(plotly)
    
    tooldf %>%
      plot_ly(
        x = ~percentage
        ,y = ~Type
        ,color = ~Var1
        ,name = ~Var1
        ,type = "bar"
        ,orientation = "h"
      ) %>%
      layout(
        barmode = "stack"
      )
    

    enter image description here