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

如何解决R语言中stat_density2d在自定义边界线左侧绘制多余内容的问题

问题解决方案

原因说明

你遇到的多余阴影是stat_density_2d的核密度平滑机制导致的:即使所有观测点都在x=40右侧,核函数的平滑带宽会让密度计算结果向x更小的方向溢出,覆盖到x<40的区间,所以才会出现左侧的半透明阴影。而geom_point仅渲染实际存在的观测点,因此左侧没有内容。

解决方案

推荐以下两种修改方式,都可以直接删除左侧多余的密度阴影:

  • 方案1:隐藏左侧区域的密度渲染(推荐,不改变右侧密度计算结果)
    直接在密度层的美学映射中,将x<40区域的透明度设为缺失值,ggplot会自动跳过这部分的渲染,不会影响右侧密度的准确性。
    如果使用支持after_stat语法的新版本ggplot(v3.3.0及以上),修改stat_density_2d的代码为:
    stat_density_2d(aes(alpha = after_stat(ifelse(x < 40, NA, density))), geom = 'tile', contour = FALSE)
    
    要是使用旧版本ggplot,可以用旧版的双下划线语法:
    stat_density_2d(aes(alpha = ifelse(..x.. < 40, NA, ..density..)), geom = 'tile', contour = FALSE)
    
  • 方案2:限制密度计算的范围
    直接给stat_density_2d设置x轴的计算范围,让核密度估计仅在x>=40的区间运行,从根源上不会生成左侧的密度结果:
    stat_density_2d(aes(alpha = ..density..), geom = 'tile', contour = FALSE, xlim = c(40, 1e4))
    

完整修改后代码(以方案1为例)

library(ggplot2)
library(scales)
visual <- ggplot(data=samples, aes(GRNHLin, REDHLin)) + 
  geom_point(colour='dodgerblue3', size=0.375) +
  # 仅修改了这一行的aes部分
  stat_density_2d(aes(alpha = after_stat(ifelse(x < 40, NA, density))), geom = 'tile', contour = FALSE) +
  scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x)), limits = c(1,1e4)) +
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x)), limits = c(1,1e3)) +
  geom_vline(xintercept=40) +
  labs(x="Green Fluorescence", y="Red Fluorescence")
visual

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:06:04