Search code examples
rgraphplotlyr-plotlystacked

How can I make a top 3 plotly stacked bar graph using R?


I love this library but I am not the best for sure! I'm trying to plot a simple stacked bar plot using plotly library in R Studio.

This is my sample data:

structure(list(parent = c("Sam", "Elena", "Sam", "Jhon", "Raul", 
"Sam", "Jhon", "Sara", "Paul", "Chris"), cost = c(4, 1, 2, 4, 
1, 2, 4, 3, 5, 6), topic = c("Banana", "Banana", "Berries", "Apple", 
"Watermelon", "Banana", "Berries", "Avocado", "Watermelon", "Pinneaple"
)), row.names = c(NA, -10L), class = "data.frame")

And this is the way I'm trying to plot it:

# Color setting
ramp2 <- colorRamp(c("deepskyblue4", "white"))
ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)

plot_ly(sample %>%
          top_n(3, `cost`), x = ~parent, y = ~cost, type = 'bar', color = ~topic ) %>%
  layout(yaxis = list(title = 'Cost'), barmode = 'stack') %>%
  add_trace(y = ~topic) %>%
  layout(colorway = ramp.list2) %>%
  config(displayModeBar = FALSE)

But there is something definitely worng because:

y axis is giving me topics and numbers, so I'm tremendously confused by that.

Legend is showing more than once each topic.

Is not plotting only top 3 based in the cost sum.

The colors showing are nothing like the ones I try to use.

Stacked Bar Chart in this link doesn't really get me going on how I can plot this graph as I want it to be. I want only 3 bars; one for Sam - 39000 (divided by two colors because he has 3 topics, but 2 are the same and I wish the line shows separating the banana color to make it look as there are two costs involved), another one for Jhon - 30000 (divided by two colors) and hte last one for Paul - 19000. Also want the legends showing to not be repeated.

This is the plot I get with that code:

plot


Solution

  • You can the error because you tried to add add_trace(y = ~topic), which is not needed when you specify barmode = 'stack'. I am not very sure about the plot you want in the end (top3 or not), but if you start with the following, it should get you going:

    library(plotly)
    library(dplyr)
    
    ramp2 <- colorRamp(c("deepskyblue4", "white"))
    ramp.list2 <- rgb( ramp2(seq(0, 1, length = 15)), max = 255)
    plot_ly(sample ,
    x = ~parent, y = ~cost, type = 'bar', color = ~topic ) %>%
      layout(list(title = 'Cost'), barmode = 'stack') %>%
      layout(colorway = ramp.list2) %>%
      config(displayModeBar = FALSE)
    

    enter image description here