0
votes

When I add a trace to a horizontal bar chart in R Plotly the additional trace is placed above the first trace, but in the legend it is vice versa. How can I place the additional trece under the first one as in the legend?

And/or how can I change the order in the legend?

bar chart

library(plotly)
library(dplyr)
df <- mtcars %>% group_by(cyl) %>% summarise_at(c('qsec','mpg'), funs(mean))


figh <- plot_ly(df, y = ~ cyl, x = ~ qsec, type = 'bar', orientation = 'h'
               ,marker = list(color = 'rgb(80, 160, 200)')
)
figh <- figh %>% add_trace(x = ~ mpg
                         ,marker = list(color = 'rgb(220, 80, 80)')
)
figh
1

1 Answers

1
votes

To change the order in the legend, you can change traceorder in legend using layout.

traceorder...

Determines the order at which the legend items are displayed. If "normal", the items are displayed top-to-bottom in the same order as the input data. If "reversed", the items are displayed in the opposite order as "normal".

https://plotly.com/r/reference/layout/#layout-legend-traceorder

layout(figh, legend = list(traceorder = "reversed"))