调整geom_col/geom_bar中fill美学映射的分组顺序问题
解决ggplot2条形图填充颜色顺序异常问题
核心原因
你的attendance是字符型变量,ggplot2默认会按字母顺序对其排序渲染,导致填充顺序不符合预期。只需明确指定attendance的顺序即可解决问题,下面提供两种可行方法:
方法1:将变量转为指定顺序的因子(推荐)
在数据处理阶段就把attendance设置为有序因子,后续绘图会自动遵循这个顺序:
library(tidyverse) # 创建数据框 group <- c('group1', 'group2','group3') never <- c(72,24,10) infrequent <- c(24,43,38) often <- c(4,33,53) df <- data.frame(group, never, infrequent, often) # 转换格式并设置因子顺序 df <- df %>% pivot_longer(cols=c('never', 'infrequent', 'often'), names_to='attendance', values_to='percent') %>% mutate(attendance = factor(attendance, levels = c('never', 'infrequent', 'often'))) # 绘图 ggplot(df, aes(x = percent, y=group, fill=attendance)) + geom_col(width=0.75, position = 'fill', color='#000000')
方法2:通过scale_fill_manual指定顺序
如果不想修改原始数据,可以在绘图时用scale_fill_manual的limits参数强制指定填充顺序,还能自定义颜色:
library(tidyverse) # 创建并转换数据框 group <- c('group1', 'group2','group3') never <- c(72,24,10) infrequent <- c(24,43,38) often <- c(4,33,53) df <- data.frame(group, never, infrequent, often) df <- df %>% pivot_longer(cols=c('never', 'infrequent', 'often'), names_to='attendance', values_to='percent') # 绘图并指定填充顺序 ggplot(df, aes(x = percent, y=group, fill=attendance)) + geom_col(width=0.75, position = 'fill', color='#000000') + scale_fill_manual( limits = c('never', 'infrequent', 'often'), # 可选:自定义颜色,示例用ggplot默认配色 values = c("#F8766D", "#00BA38", "#619CFF") )
额外注意
你的代码里library(ggplot)是错误的,应该是library(ggplot2),不过tidyverse已经包含了ggplot2,所以可以直接去掉这一行。
内容的提问来源于stack exchange,提问作者Phil Drysdale
相关产品推荐
相关产品推荐

