使用R和Plotly确定堆叠条形图中的堆叠顺序。

3

下面是使用R和Plotly制作堆叠条形图的简单示例。 默认情况下,堆栈按字母顺序排序。 我如何确定其他顺序?

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

例如,我希望能够确定类别"(order1)small value"在顶部。目前它在底部,因为按字母顺序排列时它在其他类别之前。
非常感谢您的帮助。

enter image description here

2个回答

1
在创建数据之前,请添加此行。使用category作为因子,您可以控制每个级别的顺序。
category  <-  factor(category, c("(order2)big value", "(order1)small value"))

1
非常感谢。它有效! - pep444

0
非常感谢。它有效了!在创建我的数据后,以下内容也应该有效。
data$category  <- factor(data$category, c( "(order2)big value",  "(order1)small value" )  )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接