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

R语言ggplot2的geom_col图层y轴缩放异常,柱子高度超出数据最大值

R语言ggplot2柱状图y轴刻度异常问题解决方案

问题原因

你对数据按Education字段分组后,未做聚合计算就直接绘图。geom_col()默认会对同一x分类下的所有y值求和,你的每个Education类别下都有男性、女性2条记录,最终柱子高度为两个性别薪资的总和,例如专业学位组总和为197588+138507=336095,自然远超过你设置的200000最高刻度。
另外你代码中aes()内写入的na.rm=TRUE参数位置错误,该参数不属于映射配置,需要放到几何图层或标度层中才会生效。

解决方法

方案1:提前聚合数据再绘图

先计算每个教育水平对应的平均薪资,再传入ggplot绘图:

# 先聚合计算各教育水平的平均薪资
EIS_V_Sub_Year <- EIS_V %>% 
  filter(Year == 2020) %>% 
  group_by(Education) %>% 
  summarise(MN_Salary_2020 = mean(MN_Salary_2020, na.rm = TRUE))

# 绘图代码和原逻辑保持一致即可
EIS_V_Sub_Year %>%
  ggplot(aes(x = Education, y = MN_Salary_2020, fill = Education)) + 
  geom_col(na.rm = TRUE) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) + 
  labs(
    title = "Average Salary of Full-Time Workers", 
    subtitle = "Based on Highest Level of Education in 2020", 
    caption = "Source: US Census Bureau",
    x = "Education",     
    y = "Mean Salary in Dollars (USD)"
  ) +
  scale_y_continuous(breaks = c(25000, 50000, 75000, 100000, 125000, 150000, 175000, 200000))

方案2:直接在ggplot中配置聚合逻辑

不提前处理数据,修改几何图层参数即可实现聚合绘图:

EIS_V %>%
  filter(Year == 2020) %>%
  ggplot(aes(x = Education, y = MN_Salary_2020, fill = Education)) + 
  # 用stat="summary"指定按均值聚合y值
  geom_bar(stat = "summary", fun = "mean", na.rm = TRUE) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) + 
  labs(
    title = "Average Salary of Full-Time Workers", 
    subtitle = "Based on Highest Level of Education in 2020", 
    caption = "Source: US Census Bureau",
    x = "Education",     
    y = "Mean Salary in Dollars (USD)"
  ) +
  scale_y_continuous(breaks = c(25000, 50000, 75000, 100000, 125000, 150000, 175000, 200000))

内容的提问来源于stack exchange,提问作者Kayley Bayne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:18:00