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

使用R的ggplot2绘制国家人口柱状图时遇stat_count()错误求助

问题解决:ggplot2 柱状图报错 stat_count() can only have an x or y aesthetic

错误原因

你使用geom_bar()时同时指定了x=country和y=pop,但geom_bar()默认的统计变换是stat_count()——它的作用是统计每个x类别下的观测行数,不需要手动指定y轴。当你传入具体的y值(这里是人口数)时,就和默认的计数逻辑冲突,触发报错。

修复代码

要直接使用你指定的y轴数值,需要把统计变换改为identity,或者直接用geom_col()(它是geom_bar(stat="identity")的别名,更适合展示已有数值的柱状图):

library(gapminder)
library(dplyr)
library(ggplot2) # 记得加载ggplot2包

db1 <- gapminder
db1Asia <- db1 %>% 
  filter(year %in% c(1962, 1967) & country %in% c("China", "India"))

# 修复后的1962年人口柱状图
ggplot(data = db1Asia %>% filter(year == 1962), 
       aes(x = country, y = pop, color = country, fill = country)) +
  geom_col(alpha = 0.7) # 用geom_col替代geom_bar,或者用geom_bar(stat="identity")

优化建议(更贴合你的研究需求)

既然你要对比1962-1967年两国的人口变化,可以把两年的数据放在同一幅图里,更直观:

ggplot(data = db1Asia, 
       aes(x = country, y = pop, fill = factor(year))) +
  geom_col(position = "dodge", alpha = 0.7) +
  labs(title = "1962-1967年中印人口对比",
       x = "国家", y = "人口", fill = "年份")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:35:27