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

R Shiny渲染ggplot密度图报错'x' and 'units' must have length > 0求助

R Shiny疝病BMI看板种族分组绘图报错解决方案

问题根因

  • 直接触发报错的原因是**「美洲印第安人或阿拉斯加原住民」分类仅含1例患者**,geom_density()进行核密度估计要求分组至少有2个有效观测,单样本会触发'x' and 'units' must have length > 0报错。
  • 次要潜在问题:你当前的绘图函数传参不符合ggplot的整洁评估规范,直接将外部向量传入aes映射,容易出现数据长度不匹配的隐患。
  • 之前尝试的将种族转为小写的方案无效,因为问题与字符大小写无关。

修复方案

第一步:修改density_plots函数,适配整洁评估规范+过滤小样本分组

将以下代码替换原有density.R里的density_plots函数:

density_plots <- function(dataset, variable_col, category_col, rm_na = TRUE, transparency = 0.25, lower = 0, upper = 65, title_card = "", x_label = "") {
  # 先过滤样本量小于2的分组,避免密度计算失败
  valid_groups <- dataset %>%
    count(!!sym(category_col)) %>%
    filter(n >= 2) %>%
    pull(!!sym(category_col))
  
  filtered_df <- dataset %>%
    filter(!!sym(category_col) %in% valid_groups)
  
  ggplot(data = filtered_df) + 
    geom_density(mapping = aes(x = .data[[variable_col]], color = .data[[category_col]], fill = .data[[category_col]]), na.rm = rm_na, alpha = transparency) + 
    scale_x_continuous(limits = c(lower, upper)) + 
    coord_cartesian(xlim = c(lower, upper)) +
    labs(x = x_label, title = title_card, color = category_col, fill = category_col)
}

第二步:修改server端的函数调用逻辑

将server部分的renderPlot代码替换为以下内容:

output$dense_plot = renderPlot({
  density_plots(dataset = df, 
                variable_col = input$variable, 
                category_col = input$category, 
                x_label = "BMI", 
                title_card = "Distribution of BMI", 
                lower = input$range[1], 
                upper = input$range[2])
})

可选优化

如果需要保留单样本分组的展示,可以添加判断逻辑,当分组样本量小于2时,改用geom_vline标记该样本的BMI值,或者直接在下拉选项中隐藏样本量不足的分组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:27:03