MelaniaCB
MelaniaCB

Reputation: 435

How to sort plotly stacked bar graph in r by y value?

I've got this graph and I want it to appear in Sam - Jhon - Paul order because that's going from highest to lowest cost, somebody could tell me how to order it by cost? Tried using code below in layout section but it didn't word.

 layout(yaxis = list(title = 'Cost'), 
        xaxis = list(title = 'Parent',
                     categoryorder = "array",
                     categoryarray = ~cost), 
                     barmode = 'stack') 

Upvotes: 0

Views: 1778

Answers (1)

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

You are almost there. You just need to use the order of top_3$parent in your categoryarray instead of cost, as follows:

layout(yaxis = list(title = 'Cost'), 
       xaxis = list(title = 'Parent',
               categoryorder = "array",
               categoryarray = top_3$parent), 
               barmode = 'stack')

So, using the full plotting code:

plot_ly(sample[sample$parent %in% top_3$parent,], 
        x = ~parent, y = ~cost, type = 'bar', color = ~topic) %>%
        layout(yaxis = list(title = 'Cost'), 
               xaxis = list(title = 'Parent', 
                            categoryorder = "array", 
                            categoryarray = top_3$parent), 
                            barmode = 'stack') %>%
        config(displayModeBar = FALSE)

You should get the following plot:

enter image description here

Upvotes: 1

Related Questions