# density() function not working as expected [duplicate]

I wanted to plot the density for this data:

hist(res)


As seen the max and min are -1 and 1...

But when I use

plot(density(res))


As it can be seen the density is being plotted for values higher than 1 and lower than -1, why is that? It is as if the density() function works wrong?

• Nothing wrong, except from your viewpoint. Think that the data are spikes being smoothed into bells, cones or the like, depending on kernel. A spike at the maximum will be smeared above it and a spike at the minimum will be smeared below it. The density routine can have no idea of whether values beyond extremes are attainable. Most commonly density routines are willing to smooth into impossible areas, although sometimes that is hidden by some choices on exactly what is shown. To get a density estimate that respects a support of $[-1, 1]$ or $(-1, 1)$ you would usually need extra programming. Apr 17, 2020 at 16:44
• Remember how the kernel density estimate works: adding up a bunch of Gaussian distributions. A KDE will expend past the highest and lowest values. (The “kernel” refers to the Gaussian curve. Other kernels can be selected, but the software default is Gaussian for every software I’ve seen.) The density function is doing exactly what you told it to do.
– Dave
Apr 17, 2020 at 16:46
• I am not clear that a density estimate is a good idea here at all. I would compare with a beta distribution or some such. The implication of the histogram is that the modes could be $-1$ and $1$ but I would prefer a quantile plot for a closer look. Apr 17, 2020 at 16:48
• @Dave I've seen Epanechnikov as default kernel, with good reason. Apr 17, 2020 at 16:49
• in plot(density(res)), what does y axis respresent? I thought it was 'probability' but I see values higher than 1... Apr 17, 2020 at 22:27