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

R中用ggplot绘制微生物相对丰度时遇整数对象高度获取错误求助

R ggplot绘制微生物相对丰度报错:Error in FUN():! Don't know how to get height of <integer> object

问题复现

以下代码基于phyloseq自带的GlobalPatterns数据集完整复现错误(R版本4.4.0):

library(phyloseq)
library(ggplot2)

# 加载示例数据集
data(GlobalPatterns)
ps_rar <- GlobalPatterns

# 聚合到属水平
ps_genus <- tax_glom(ps_rar, taxrank = "Genus")

# 筛选丰度前20的属
top20_genera <- names(sort(taxa_sums(ps_genus), decreasing = TRUE))[1:20]
ps_genus_top20 <- prune_taxa(top20_genera, ps_genus)

# 新增Genus_20列标记分类
tax_table(ps_genus_top20)$Genus_20 <- ifelse(tax_table(ps_genus_top20)[, "Genus"] %in% top20_genera, 
                                            as.character(tax_table(ps_genus_top20)[, "Genus"]), 
                                            "Other")

# 转换为相对丰度
ps_rel <- transform_sample_counts(ps_genus_top20, function(x) x / sum(x))

# 转换为数据框
df_rel <- psmelt(ps_rel)

# 触发错误的绘图代码
ggplot(df_rel, aes(x = Sample, y = Abundance, fill = Genus_20)) +
  geom_bar(stat = "identity")

错误回溯(rlang::last_trace()输出):

<error/rlang_error>
Error in FUN():! Don't know how to get height of <integer> object
---
Backtrace:
 1. ggplot2::ggplot(...)
 2. ggplot2:::ggplot.default(...)
 3. ggplot2:::layer(data = data, mapping = mapping, stat = stat, geom = geom, ...)
 4. ggplot2::geom_bar(stat = "identity")
 5. ggplot2:::layer(data = data, mapping = mapping, stat = stat, geom = geom, ...)
 6. ggplot2:::geom_identity(...)
 7. ggplot2::GeomBar$draw_panel(data, panel_params, coord)
 8. ggplot2:::collide(data, padding, direction, "position_stack")
 9. ggplot2:::collide2(data, padding, direction)
10. ggplot2:::get_height(data)

原因分析

该错误源于R 4.4.0的类型检查严格性升级与ggplot2旧版本/phyloseq类型转换不彻底的冲突:

  1. transform_sample_counts()执行相对丰度转换后,phyloseq对象的OTU表仍保留整数类型(尽管计算结果是小数,但R的整数除法/赋值逻辑未自动转为数值型)
  2. psmelt()直接沿用该整数类型输出Abundance列
  3. ggplot2的geom_bar(stat="identity")在处理整数类型的y轴变量时,因新版本R的类型约束触发高度获取失败的错误

验证方式:运行class(df_rel$Abundance)会返回integer,但相对丰度应为numeric类型。

解决方案

方案1:手动转换Abundance列类型(最快临时修复)

在psmelt()后添加一行代码,将整数转为数值型:

df_rel$Abundance <- as.numeric(df_rel$Abundance)

之后再执行ggplot绘图即可正常运行。

方案2:修改相对丰度转换逻辑,强制返回数值型

调整transform_sample_counts()的转换函数,确保输出为数值类型:

ps_rel <- transform_sample_counts(ps_genus_top20, function(x) as.numeric(x / sum(x)))

后续psmelt()输出的Abundance会直接是数值型,无需额外转换。

方案3:更新ggplot2到最新版本

运行以下命令更新ggplot2,新版本已适配R 4.4.0的类型处理规则:

install.packages("ggplot2")

验证修复

以方案1为例,修复后完整绘图代码:

df_rel$Abundance <- as.numeric(df_rel$Abundance)
ggplot(df_rel, aes(x = Sample, y = Abundance, fill = Genus_20)) +
  geom_bar(stat = "identity") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:20:35