如何在ggplot2中控制颜色映射?堆叠条形图颜色与图例错位问题
解决堆叠条形图颜色与图例不匹配问题
你遇到的颜色反转问题,根源在于**aes(fill = rev(BAR_CHOICES))将填充分组的顺序反转,但scale_fill_manual仍按原分组顺序映射颜色**,导致图表颜色和图例对应关系颠倒。结合你需要保留条形顺序、标注正确的需求,有两种简洁的修复方式:
方式一:移除fill中的rev,通过调整堆叠顺序保持现有条形布局
如果希望保留当前的条形堆叠顺序(从下到上对应None→thepast→lastyear→thisyear→nextyear),可以去掉aes里的rev(),改用position_stack(reverse=TRUE)来控制堆叠方向:
output$distPlot <- renderPlot({ ggplot( bardata , aes(x = NA, y = total_count, fill = BAR_CHOICES, label = total_count)) + geom_col(position = position_stack(reverse = TRUE)) + # 新增reverse参数控制堆叠方向 scale_fill_manual(values = setNames(c('black','#6f7171','#ff8027','#ffe97a','#006fc1','#dcf5e6','#008331'),c('None', thepast,lastyear, thisyear, nextyear,nextyear2,future))) + geom_text(position = position_stack(reverse = TRUE, vjust = 0.5), size = 4.5, color = "black", fontface="bold") + # 文本位置同步反转 guides(fill = guide_legend(reverse=FALSE , nrow=2)) + coord_flip() + scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) + theme(axis.line=element_blank(), axis.text.x=element_blank(), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), legend.position="bottom", legend.title=element_blank() , legend.text=element_text(size=12), panel.background=element_blank(), panel.border=element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), plot.background=element_blank()) + ggtitle("Estimated Solution Completion") }, height=150)
方式二:反转scale_fill_manual的颜色顺序,匹配fill的rev()
如果想保留aes(fill = rev(BAR_CHOICES)),只需将scale_fill_manual的颜色值列表反转,让颜色映射和反转后的分组对应:
output$distPlot <- renderPlot({ ggplot( bardata , aes(x = NA, y = total_count, fill = rev(BAR_CHOICES), label = total_count)) + geom_col() + # 反转颜色值列表,匹配rev(BAR_CHOICES)的分组顺序 scale_fill_manual(values = setNames(rev(c('black','#6f7171','#ff8027','#ffe97a','#006fc1','#dcf5e6','#008331')),c('None', thepast,lastyear, thisyear, nextyear,nextyear2,future))) + geom_text(position = position_stack(vjust = 0.5), size = 4.5, color = "black", fontface="bold") + guides(fill = guide_legend(reverse=FALSE , nrow=2)) + coord_flip() + scale_x_discrete(expand = c(0, 0)) + scale_y_discrete(expand = c(0, 0)) + theme(axis.line=element_blank(), axis.text.x=element_blank(), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), legend.position="bottom", legend.title=element_blank() , legend.text=element_text(size=12), panel.background=element_blank(), panel.border=element_blank(), panel.grid.major=element_blank(), panel.grid.minor=element_blank(), plot.background=element_blank()) + ggtitle("Estimated Solution Completion") }, height=150)
两种方式都能让图表颜色和图例保持一致,推荐第一种方式,因为它更直观地通过堆叠位置控制布局,避免分组和颜色映射的混淆。
内容的提问来源于stack exchange,提问作者Eddie Rowe
相关产品推荐
相关产品推荐

