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

R语言函数内使用geom_vline绘图报参数非数值逻辑错误如何解决

错误原因
  • 调用函数时传入的predictor和outcome都是字符串类型的列名,函数内部直接使用predictor[outcome == 'no']时,R会将两个参数直接当作字符串处理,而非数据集中对应的列,因此无法计算均值,返回NA并触发报错。
  • 原代码中第一根参考线的color参数值'999999'缺少前缀#,会导致样式渲染异常。
修复方案

提前在函数内提取对应列计算好两组均值,再直接传入geom_vline的xintercept参数即可,无需在aes_string内做均值计算,避免列名解析异常。修复后的完整代码如下:

library(ggplot2)
library(ggthemes)
library(gridExtra)
library(dplyr)

plot_numeric <- function(dataset, predictor, outcome){
  # 提前提取对应列,计算两组均值
  pred_col <- dataset[[predictor]]
  out_col <- dataset[[outcome]]
  mean_no <- mean(pred_col[out_col == 'no'])
  mean_yes <- mean(pred_col[out_col == 'yes'])

  p1 <- dataset %>% ggplot(aes_string(x = predictor)) + 
                    geom_density(fill = 'gray', alpha = 0.5) +
                    theme_fivethirtyeight()
  
  p2 <- dataset %>% ggplot(aes_string(x = predictor, fill = outcome)) +
                    geom_density(alpha = 0.5) +
                    scale_fill_manual(values = c('#999999', '#E69F00')) +
                    # 直接传入预计算的均值,不需要嵌套在aes_string中
                    geom_vline(xintercept = mean_no, color = '#999999') +
                    geom_vline(xintercept = mean_yes, color = '#E69F00') +
                    theme_fivethirtyeight()
  
  grid.arrange(p1,p2)
}

# 测试调用
diabetes <- data.frame(Age = c(20,23,45,77), Diabetes = c('no', 'no', 'yes', 'yes'))
plot_numeric(diabetes, 'Age', 'Diabetes')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:06:06