You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:00:57