Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine the stack order in a stacked bar plot with r and plotly

below is a simple example for stacked bar plot with r and plotly. By default, the stacks are alphabetly ordered. How can I determine other order?

library(plotly) 
bars <- c("bar1", "bar1", "bar2", "bar2")
category <- c("(order1)small value", "(order2)big value", "(order1)small value", "(order2)big value")
#category <- c("(order2)small value", "(order1)big value", "(order2)small value", "(order1)big value")
count <- c(3, 6, 2, 7)
data <- data.frame(bars, category, count)
#View(data)
p <- plot_ly(data,  x = ~bars, y = ~count, color = ~category) %>% 
layout(width = 460, height = 230, barmode = 'stack' ) 
p

E.g. I would like to be able to determine, that the category: "(order1)small value" to be on the top. Now it is on the bottom, because alphabetly it is before the other category.

Thank you very much in advance

enter image description here

like image 776
pep444 Avatar asked Nov 04 '25 22:11

pep444


1 Answers

Add this line before creating you data. With category as a factor you can controle the order of each level.

category  <-  factor(category, c("(order2)big value", "(order1)small value"))
like image 193
Johan Rosa Avatar answered Nov 07 '25 16:11

Johan Rosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!