修复ggplot2堆叠柱状图setup_params()函数y轴映射错误
解决ggplot堆叠柱状图的y轴数值错误与stat_count报错问题
问题背景
使用如下结构的数据框绘制堆叠柱状图:
df = structure(list(Year_Publication = c(1989L, 1994L, 2001L, 2002L, 2002L, 2004L, 2006L, 2007L, 2009L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 2020L, 2021L, 2021L, 2022L, 2022L, 2022L, 2022L), Taxa = c("Cervidae", "Teleostei", "Chondrichtyes", "Chondrichtyes", "Gastropoda", "Teleostei", "Malacostraca", "Teleostei", "Teleostei", "Teleostei", "Teleostei", "Teleostei", "Teleostei", "Teleostei", "Teleostei", "Chondrichtyes", "Teleostei", "Chondrostei", "Teleostei", "Chondrichtyes", "Decapoda", "Teleostei", "Gastropoda", "Chondrichtyes", "Chondrostei", "Teleostei", "Bivalvia", "Tetrapoda", "Teleostei", "Orthoptera", "Chondrichtyes", "Teleostei", "Reptilia", "Bovidae"), Total_Species_Per_Taxa = c(1L, 2L, 1L, 1L, 3L, 1L, 1L, 1L, 2L, 4L, 2L, 1L, 1L, 2L, 4L, 2L, 4L, 1L, 7L, 3L, 1L, 6L, 1L, 3L, 1L, 7L, 2L, 1L, 1L, 1L, 4L, 4L, 1L, 1L), Total_Species_Per_Pub = c(1L, 2L, 1L, 4L, 4L, 1L, 1L, 1L, 2L, 4L, 2L, 1L, 1L, 2L, 4L, 7L, 7L, 7L, 11L, 11L, 11L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 2L, 2L, 10L, 10L, 10L, 10L)), class = "data.frame", row.names = c(NA, -34L))
尝试以下两段代码时触发错误:
ggplot(data = taxa_diversity, aes(x = `Year_Publication`, fill = Taxa)) + geom_bar(aes(y = `Total_Species_Per_Pub`), stat = "count")
ggplot(data = taxa_diversity, aes(x = `Year_Publication`, y = `Total_Species_Per_Pub`, fill = Taxa)) + geom_bar(stat = "count")
错误信息:
Error in `geom_bar()`: ! Problem while computing stat. ℹ Error occurred in the 1st layer. Caused by error in `setup_params()`: ! `stat_count()` must only have an x or y aesthetic. Run `rlang::last_error()` to see where the error occurred.
移除y轴设置后图表可生成,但y轴数值不符合预期。
解决方案
1. 报错原因
stat="count"的作用是统计x/y轴每个分组的行数,它不需要手动指定y轴数值。当你同时指定y轴和stat="count"时,ggplot会因为逻辑冲突抛出错误。移除y轴后,它默认统计每年每个Taxa的行数,这和你需要的物种数量数值不符,所以y轴显示错误。
2. 正确代码
你的数据已经是汇总好的(每个Year_Publication+Taxa对应的物种数Total_Species_Per_Taxa,且同一年份的该数值之和等于Total_Species_Per_Pub),因此需要使用stat="identity",告诉ggplot直接使用y轴指定的数值绘制柱子:
ggplot(data = df, aes(x = Year_Publication, y = Total_Species_Per_Taxa, fill = Taxa)) + geom_bar(stat = "identity")
3. 补充说明
- 这段代码会生成堆叠柱状图,每个年份柱子的总高度等于该年份的
Total_Species_Per_Pub,每个分段对应不同Taxa的Total_Species_Per_Taxa,符合你的数据逻辑。 - 如果需要调整图表样式(比如添加标签、修改颜色、调整坐标轴),可以在代码后继续添加
labs()、scale_fill_manual()等图层。
内容的提问来源于stack exchange,提问作者Kristen Cyr
相关产品推荐
相关产品推荐

