Search code examples
rclasskernel-densityprobability-densitydensity-plot

plotting points on kernel density function unsuccessful in R


I'm trying to get some points on my density plot for the seq(-3, 3) [i.e., 7 numbers]. I get the 7 corresponding density values but when I try to execute points, I get:

Error in xy.coords(x, y) : 'x' and 'y' lengths differ

As really there is no length difference, I assume there is class() difference problem between x, and y for points(). I appreciate a solution?

Here is the R code:

positions = rnorm(1e4)

DENS = density(positions, adjust = 2, n = 1e4)

x.DENS = DENS$x
y.DENS = DENS$y

plot( DENS, col = "red", lwd = 3, xlab = "Positions",
  ylab = "Density", xlim = c(-6, 6), main = 
  NA, bty = 'n', zero.line = F)

x.DENS.2 = seq(-3, 3)
y.DENS.2 = approx(x.DENS, y.DENS, xout = x.DENS.2 ) ## get the x.DENS.2 density values

points(x.DENS.2, y.DENS.2) ## Error 

Solution

  • The y.DENS.2-object is actually a list with x and y components:

    str(y.DENS.2 )
    List of 2
     $ x: int [1:7] -3 -2 -1 0 1 2 3
     $ y: num [1:7] 0.00514 0.0642 0.23952 0.37896 0.24057 ...
    

    ... so you can just use

    points(y.DENS.2, col="blue")
    

    enter image description here