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

编写R函数并排绘制箱线图与密度图却得到空图,求原因

空图问题的原因及修正方案

你的R函数出现空图,主要是以下几个问题导致的:

  • ggplot映射逻辑错误
    你想对比二元分组y下cell.type的分布,但箱线图的aes把数值型的cell.type放在x轴,分组仅作为填充色,这会让ggplot试图为每个cell.type的数值单独画箱子,完全偏离需求;密度图虽然x轴是cell.type,但没有正确关联分组列,导致无法区分两组分布。

  • 参数引用方式错误
    你传入的y是字符串(比如"PD"),但函数里直接写as.factor(y),这会把字符串"PD"本身转为因子(所有数据都属于同一个水平),而不是取数据框中名为PD的列,分组逻辑完全失效。

  • 标题函数使用错误
    ggplot中设置标题要用ggtitle(),基础R的title()对ggplot对象无效,不仅不会显示标题,还可能引发隐性错误。

  • 数据合并的潜在风险
    merge(..., by=0, all=TRUE)会按行名合并两个数据集,如果scores和mydata的行名不匹配,合并后会产生大量NA,再经过na.omit()可能直接清空数据,导致无图可画。


修正后的函数

library(ggplot2)
library(cowplot)
library(dplyr)
library(rlang)

density_and_boxplot = function(data = data, metadata = metadata, cell.type = 'cell.type', y = "") {
  # 只合并行名匹配的行,避免无效数据
  combination = merge(data, metadata, by=0, all=FALSE) %>% na.omit()
  
  # 提前检查数据是否有效
  if(nrow(combination) == 0) stop("合并后无有效数据,请检查两个数据集的行名是否匹配")
  
  # 箱线图:按y分组,展示cell.type的分布
  p1 = ggplot(data = combination, aes(x=as.factor(!!sym(y)), y=!!sym(cell.type), fill=as.factor(!!sym(y)))) +
    geom_boxplot() +
    ggtitle(paste('箱线图:', cell.type)) +
    labs(x = y, y = cell.type)
  
  # 密度图:按y分组,展示cell.type的密度分布
  p2 = ggplot(data = combination, aes(x=!!sym(cell.type), fill=as.factor(!!sym(y)))) +
    geom_density(alpha=.5) +
    ggtitle(paste('密度分布:', cell.type)) +
    labs(x = cell.type, fill = y)
  
  return(cowplot::plot_grid(p1,p2))
}

调用方式(和之前一致)

density_and_boxplot(data = scores, metadata = mydata, cell.type = 'B-cells', y = 'PD')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:48:22