R语言如何按分组n或share数值填充百分比堆叠条形图
R 百分比堆叠条形图按数值映射填充色解决方案
问题根因
你修改fill映射为factor(n, ordered = T)后,ggplot默认会将fill变量作为堆叠分组的依据,你的数据中1月和12月的n值相同(均为14),会被判定为同一组,导致堆叠时块合并、顺序错乱,也和geom_text指定的group=month的位置无法匹配。
解决方法
显式指定堆叠分组依据为month,保证堆叠顺序和文本位置和最初版本一致,fill参数单独映射n或share即可实现按数值大小匹配填充色的需求。
示例1:按share(占比)映射连续填充色
library(ggplot2) library(glue) ggplot(df, aes(x = x, y = share, group = month)) + geom_bar( aes(fill = share), position = "fill", stat = "identity", color = "black", show.legend = F ) + geom_text( aes(label = glue("{month}: {round(share, 2)}")), position = position_stack(vjust = .5) ) + # 连续数值使用viridis连续色阶 scale_fill_viridis_c() + theme_void()
示例2:按n(计数)映射有序离散填充色
如果需要按n的有序因子映射填充色,仅需修改geom_bar的fill参数和色阶函数即可:
ggplot(df, aes(x = x, y = share, group = month)) + geom_bar( aes(fill = factor(n, ordered = T)), position = "fill", stat = "identity", color = "black", show.legend = F ) + geom_text( aes(label = glue("{month}: {round(share, 2)}")), position = position_stack(vjust = .5) ) + # 有序离散值使用viridis离散色阶 scale_fill_viridis_d() + theme_void()
内容的提问来源于stack exchange,提问作者Lenn
相关产品推荐
相关产品推荐

