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

在R/ggplot2中生成层次聚类碎石图报错求助

解决层次聚类碎石图的代码错误

错误原因

tibble 3.0.0+ 不再允许直接将数值向量传入as.tibble(),必须明确将向量转换为单列数据框,否则会触发argument ".data" is missing的错误。你的代码中myhclust$height是一个数值向量,直接用as.tibble()处理不符合新版本tibble的要求。

可行解决方案

方案1:直接用tibble()构造数据框(推荐)

这种写法更直观,避免向量转数据框的兼容性问题:

# 先加载必要的包
library(tidyverse)

# 构造碎石图所需的数据
scree_df <- tibble(
  height = myhclust$height,
  groups = length(myhclust$height):1
)

# 绘制碎石图
ggplot(scree_df, aes(x = groups, y = height)) +
  geom_point() +
  geom_line()

方案2:用as_tibble_col()适配向量转数据框

如果偏好管道写法,可以用tibble包的as_tibble_col()函数明确将向量转为单列数据框:

library(tidyverse)

myhclust$height %>%
  as_tibble_col(column_name = "height") %>%
  mutate(groups = length(myhclust$height):1) %>%
  ggplot(aes(x = groups, y = height)) +
  geom_point() +
  geom_line()

注意事项

  • 确保已安装并加载tidyverse(或单独的ggplot2、dplyr、tibble包)
  • myhclust必须是合法的hclust对象,可通过class(myhclust)确认类型

内容的提问来源于stack exchange,提问作者laurent-bourbaki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:16:00