简体   繁体   中英

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) [ie, 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 

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

在此输入图像描述

The last line is incorrect. Please change it to

points(x.DENS.2, y.DENS.2$y)

Here is the full codes. It works on my side. So, when you plot the results, it will be very helpful to check the dimension of your inputs to make sure that they matched.

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$y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM