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

R语言如何从密度图提取不同百分位特征匹配原始data.frame

分位特征提取实现方案

不要从可视化结果里反推数据,直接基于原始Delta数据集计算分位阈值、匹配对应特征即可,结果精度远高于图像提取。

核心实现步骤

  • 计算目标分位阈值
    用base R内置的quantile()函数直接计算25%、50%、75%三个分位对应的PC1-PC2差值,自动忽略缺失值:
    library(dplyr)
    library(ggplot2)
    
    # 计算四分位阈值,依次对应Q1(25%)、中位数(50%)、Q3(75%)
    q_thresholds <- quantile(Delta$`PC1-PC2`, probs = c(0.25, 0.5, 0.75), na.rm = TRUE)
    
  • 提取分位对应特征存入新数据框
    根据分析需求二选一即可:
    # 方案1:提取距离每个分位阈值最近的单基因/特征,适合做分位锚点标记
    quantile_anchor <- Delta %>%
      summarise(
        quantile = c("25%", "50%", "75%"),
        threshold_val = c(q_thresholds[1], q_thresholds[2], q_thresholds[3]),
        gene_symbol = c(
          Gene_Symbols[which.min(abs(`PC1-PC2` - q_thresholds[1]))],
          Gene_Symbols[which.min(abs(`PC1-PC2` - q_thresholds[2]))],
          Gene_Symbols[which.min(abs(`PC1-PC2` - q_thresholds[3]))]
        ),
        actual_diff_val = c(
          `PC1-PC2`[which.min(abs(`PC1-PC2` - q_thresholds[1]))],
          `PC1-PC2`[which.min(abs(`PC1-PC2` - q_thresholds[2]))],
          `PC1-PC2`[which.min(abs(`PC1-PC2` - q_thresholds[3]))]
        )
      )
    
    # 方案2:按分位区间给所有特征打标签,适合分组建模/差异分析
    Delta_with_quantile_tag <- Delta %>%
      mutate(
        quantile_group = case_when(
          `PC1-PC2` <= q_thresholds[1] ~ "0-25%",
          `PC1-PC2` > q_thresholds[1] & `PC1-PC2` <= q_thresholds[2] ~ "25%-50%",
          `PC1-PC2` > q_thresholds[2] & `PC1-PC2` <= q_thresholds[3] ~ "50%-75%",
          `PC1-PC2` > q_thresholds[3] ~ "75%-100%"
        )
      )
    
  • 和原始数据做映射匹配
    用Gene_Symbols作为关联键直接关联即可,不会出现匹配错位:
    # 锚点特征匹配原始表全量信息
    anchor_mapped <- quantile_anchor %>%
      left_join(Delta, by = c("gene_symbol" = "Gene_Symbols"))
    

结果校验(可选)

可以把分位位置标注到原来的组合图上,确认提取结果和可视化位置一致:

# 密度图加标注
p1 <- ggdensity(Delta, x = "PC1-PC2", fill = "#87CEFA", alpha = 0.7) +
  geom_vline(xintercept = q_thresholds, linetype = "dashed", color = c("#1E90FF", "#DC143C", "#1E90FF"), linewidth = 0.8)

# 箱线图加标注
p2 <- ggplot(Delta, aes(x = "", y = `PC1-PC2`)) +
  geom_boxplot(width = 0.4) +
  geom_point(data = quantile_anchor, aes(x = "", y = actual_diff_val), color = "#DC143C", size = 2.5) +
  xlab("")

# 组图输出
egg::ggarrange(p1, p2, ncol = 2)

注意:如果存在多个特征的PC1-PC2值完全等于分位阈值,上述代码会自动识别所有匹配记录;如果不需要实际观测的特征值,仅需要分位统计量,直接使用quantile()返回的计算结果即可,不需要做特征匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 03:27:52