如何按 y 值对 r 中的堆积条形图进行排序?

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

我有 ,我希望它出现在 Sam - Jhon - Paul 顺序中,因为这是从最高到最低成本,有人可以告诉我如何按成本订购?尝试使用下面 layout 部分中的代码,但它没有字。

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

你快到了。你只需要在你的categoryarray中使用top_3$parent的顺序而不是cost,如下:

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

因此,使用完整的绘图代码:

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)

你应该得到以下情节: