【问题标题】:How to remove curves after last datapoint in ggplot2如何在ggplot2中的最后一个数据点之后删除曲线
【发布时间】:2025-12-02 14:10:02
【问题描述】:

我想擦除 ggplot 中没有数据点的地方的密度曲线的一部分。 如果添加密度曲线,程序会自动添加密度估计曲线。 我必须擦除最后一个数据点之后的部分。有多条曲线,因此不能选择将范围设置为 x 轴。 例如,在示例虹膜数据中,我想删除标记为橙色的部分。

library(ggplot2)
library(dplyr)
data(iris)
summary(iris)

setosa <- iris %>%filter(Species== 'setosa')
versicolor <- iris %>%filter(Species== 'versicolor')
virginica <- iris %>%filter(Species== 'virginica')

summary(setosa)
summary(versicolor)
summary(virginica)

p <- ggplot(setosa, aes(x = Sepal.Length, colour = Species)) + 
  geom_density()
p

【问题讨论】:

  • 这能回答你的问题吗? ggplot2 and geom_density: how to remove baseline?
  • @s_t 类似,但不是欺骗,在尝试建议的答案时,行不会“触摸”x 轴为零。试试看:ggplot(iris, aes(x = Sepal.Length, colour = Species)) + stat_density(geom = "line")
  • @zx8754 撤回了接近投票,谢谢。
  • 尝试在geom_density() 中添加trim = TRUE?还是您的用例如此具体,以至于您想保留一端而修剪另一端?

标签: r ggplot2 kernel-density


【解决方案1】:

以下方法远非理想,但这是我想出的解决方案,所以我们开始吧。它基本上使用 ggplot2 v3.3.0 中引入的修改器系统来使数据点超出您的限制NAs,这些数据点会自动删除。

suppressPackageStartupMessages({
  library(ggplot2)
  library(dplyr)
})
#> Warning: package 'ggplot2' was built under R version 4.0.2

data(iris)

setosa <- iris %>%filter(Species== 'setosa')
versicolor <- iris %>%filter(Species== 'versicolor')
virginica <- iris %>%filter(Species== 'virginica')

ggplot(mapping = aes(x = Sepal.Length, colour = Species)) + 
  geom_density(data = setosa,
               aes(x = stage(Sepal.Length, after_stat = ifelse(x > 5.8, NA, x)))) +
  geom_density(data = versicolor,
               aes(x = stage(Sepal.Length, after_stat = ifelse(x > 7, NA, x)))) +
  geom_density(data = virginica,
               aes(x = stage(Sepal.Length, after_stat = ifelse(x > 7.9, NA, x))))

reprex package (v0.3.0) 于 2020 年 7 月 7 日创建

另一种策略是使用 stats::density() 预先计算您的密度,然后手动切割它们。

【讨论】: