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

亡梦爱人 提交于 2020-03-26 04:04:56

问题


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') 

回答1:


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:



来源:https://stackoverflow.com/questions/60310790/how-to-sort-plotly-stacked-bar-graph-in-r-by-y-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!