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

落花浮王杯 提交于 2019-12-02 05:28:33

By default, density will extend the range so that the density curve approaches 0 at the extreme. Do you want to restrict the curve to the range of you data? If so, you need use from and to arguments inside density().

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])

Perhaps it is better to provide a reproducible example.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!