You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言Plotly堆叠条形图中自定义堆叠顺序

自定义Plotly堆叠条形图的堆叠顺序

要将(order1)small value类别置于堆叠顶部,有两种简单的实现方式:

方法1:通过因子水平控制顺序

将category列转换为因子,并指定自定义的水平顺序——想要在堆叠底部的类别放在前面,顶部的放在后面,Plotly会遵循因子的顺序完成堆叠。

修改后的完整代码:

library(plotly) 
bars <- c("bar1", "bar1", "bar2", "bar2")
category <- c("(order1)small value", "(order2)big value", "(order1)small value", "(order2)big value")
count <- c(3, 6, 2, 7)
data <- data.frame(bars, category, count)

# 将category转为因子,指定堆叠顺序:底部是(order2)big value,顶部是(order1)small value
data$category <- factor(data$category, levels = c("(order2)big value", "(order1)small value"))

p <- plot_ly(data,  x = ~bars, y = ~count, color = ~category) %>% 
layout(width = 460, height = 230, barmode = 'stack' ) 
p

方法2:直接在Plotly中指定类别顺序

无需修改数据结构,在plot_ly()函数中通过categoryorder和categoryarray参数直接定义堆叠顺序:

修改后的完整代码:

library(plotly) 
bars <- c("bar1", "bar1", "bar2", "bar2")
category <- c("(order1)small value", "(order2)big value", "(order1)small value", "(order2)big value")
count <- c(3, 6, 2, 7)
data <- data.frame(bars, category, count)

p <- plot_ly(data,  x = ~bars, y = ~count, color = ~category,
             categoryorder = "array",
             categoryarray = c("(order2)big value", "(order1)small value")) %>% 
layout(width = 460, height = 230, barmode = 'stack' ) 
p

两种方法都能实现目标:方法1更适合需要在后续分析中保持类别顺序的场景,方法2则更灵活,无需改动原始数据。

内容的提问来源于stack exchange,提问作者pep444

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:20:43