`plot.density` 将 "xlim" 扩展到我的数据范围之外。为什么以及如何解决它?

`plot.density` extends "xlim" beyond the range of my data. Why and how to fix it?

使用下面的代码,我试图获取不同分布的密度图。

dens <- apply(df[,c(7,9,12,14,16,18)], 2, density)

plot(NA, xlim=range(sapply(dens, "[", "x")), ylim=range(sapply(dens, "[", "y")))
mapply(lines, dens, col=1:length(dens))

legend("topright", legend=names(dens), fill=1:length(dens),bty = "n",lwd=1, cex=0.7)

所有变量的最大上限是 5。但是我得到的行超过了 5。我需要在我的代码中更改什么来修复绘图?

默认情况下,density 将扩大范围,使密度曲线在极值处接近 0。你想将曲线限制在你的数据范围内吗?如果是这样,您需要在 density().

中使用 fromto 参数
x_range <- range(df[,c(7,9,12,14,16,18)])
dens <- apply(df[,c(7,9,12,14,16,18)], 2, density, from = x_range[1], to = x_range[2])

也许最好提供一个可重现的例子。

set.seed(0); X <- matrix(rnorm(300), 100, 3)

## range of your data
x_range <- range(X)
# [1] -2.904899  2.658658

## default handling of `density`
dens <- apply(X, 2, density)
range(sapply(dens, "[[", "x"))
# [1] -3.922346  3.696451

## customized `from` and `to`
dens <- apply(X, 2, density, from = x_range[1], to = x_range[2])
range(sapply(dens, "[[", "x"))
# [1] -2.904899  2.658658