Home > Back-end >  determine the stack order in a stacked bar plot with r and plotly
determine the stack order in a stacked bar plot with r and plotly

Time:10-11

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

CodePudding user response:

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

CodePudding user response:

Thnak you very much. It works! The following after creating my data should also work.

data$category  <- factor(data$category, c( "(order2)big value",  "(order1)small value" )  )
  • Related