ggplot柱状图X轴填充与数值分配错误:柱状值过高求助
ggplot柱状图数值异常偏高与填充效果调整方案
问题根源
你当前代码里的geom_bar(stat='identity')默认是堆叠模式,会把同一个Count下三个Type的Hours数值直接相加,比如Beu的三个值加起来约124,这就导致柱子高度远超单组的40左右。
解决办法
1. 并列分组柱状图(推荐,符合你要的"叠加填充"展示不同Type的需求)
如果想让每个Count下的不同Type以独立柱子并列展示,给geom_bar加上position = "dodge"参数即可:
library(tidyverse) df %>% mutate(Type = as.factor(Type)) %>% ggplot(aes(x = Count, y = Hours, fill = Type)) + geom_bar(stat = 'identity', position = position_dodge(width = 0.8)) + coord_flip() + theme_classic()
2. 堆叠占比柱状图(若需展示各Type的相对占比)
要是你确实需要堆叠效果,但不想总和超过100,可以先把每个Count下的Hours归一化,转成百分比占比:
library(tidyverse) df %>% mutate(Type = as.factor(Type)) %>% group_by(Count) %>% mutate(Hours_percent = Hours / sum(Hours)) %>% ggplot(aes(x = Count, y = Hours_percent, fill = Type)) + geom_bar(stat = 'identity') + coord_flip() + theme_classic() + scale_y_continuous(labels = scales::percent)
3. 合并Count与Type作为横轴(单柱对应单个Type)
如果希望每个柱子对应一个Count+Type组合,直接把两者合并成横轴变量:
library(tidyverse) df %>% mutate(Type = as.factor(Type)) %>% ggplot(aes(x = paste(Count, Type, sep = "-"), y = Hours, fill = Type)) + geom_bar(stat = 'identity') + coord_flip() + theme_classic() + labs(x = "Count-Type")
内容的提问来源于stack exchange,提问作者Nuñes
相关产品推荐
相关产品推荐

