简体   繁体   English

在R中绘制核密度函数点不成功的点

[英]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]. 我想在seq(-3, 3) [即7个数字]的密度图上得到一些points I get the 7 corresponding density values but when I try to execute points , I get: 我得到了7个相应的密度值但是当我尝试执行points ,我得到:

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() . 实际上没有长度差异,我假设在x和y之间存在class()差异问题,对于points() I appreciate a solution? 我很欣赏解决方案?

Here is the R code: 这是R代码:

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: y.DENS.2实际上是一个包含x和y组件的列表:

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) 分(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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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