调整ggplot2堆叠条形图层级顺序,使cars层级优先于bicyclis显示
解决堆叠条形图层级顺序问题
你当前的代码存在两个关键问题:
- 使用了
position = "identity",这会让两个类别的条形重叠显示,而非堆叠 - 虽然已经设置了因子层级,但错误的position参数导致堆叠效果未生效
修改后的代码
library(ggplot2) library(reshape2) # Generate artificial data set.seed(123) deciles <- rep(1:10, 2) variable <- rep(c("cars", "bicyclis"), each = 10) value <- runif(20, min = 0, max = 100) # Create data frame df <- data.frame(deciles, variable, value) df$variable <- factor(df$variable, levels = c("cars", "bicyclis")) ggplot(df, aes(x = factor(deciles), y = value, fill = variable)) + geom_bar(stat = "identity", position = "stack") + scale_fill_manual(values = c("royalblue", "red"))
关键说明
- 将
position = "identity"改为position = "stack",启用堆叠条形图效果 - 你已经正确设置了
variable的因子层级c("cars", "bicyclis"),ggplot默认会按照因子层级从下到上堆叠:- 蓝色的
cars会显示在堆叠的底层(第一层) - 红色的
bicyclis会显示在堆叠的上层(第二层)
- 蓝色的
如果后续需要反转堆叠顺序,只需将position改为position_stack(reverse = TRUE)即可。
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

