在R中不成功的核密度函数绘图点
plotting points on kernel density function unsuccessful in R
我正在尝试在我的 seq(-3, 3)
[即 7 个数字] 的密度图上得到一些 points
。我得到了 7 个相应的密度值,但是当我尝试执行 points
时,我得到:
Error in xy.coords(x, y) : 'x' and 'y' lengths differ
由于确实没有长度差异,我假设 points()
的 x 和 y 之间存在 class()
差异问题。
我感谢解决方案?
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
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 ...
...所以你可以使用
points(y.DENS.2, col="blue")
最后一行不正确。请将其更改为
points(x.DENS.2, y.DENS.2$y)
这是完整的代码。它对我有用。因此,当您绘制结果时,检查输入的维度以确保它们匹配将非常有帮助。
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)
我正在尝试在我的 seq(-3, 3)
[即 7 个数字] 的密度图上得到一些 points
。我得到了 7 个相应的密度值,但是当我尝试执行 points
时,我得到:
Error in xy.coords(x, y) : 'x' and 'y' lengths differ
由于确实没有长度差异,我假设 points()
的 x 和 y 之间存在 class()
差异问题。
我感谢解决方案?
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
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 ...
...所以你可以使用
points(y.DENS.2, col="blue")
最后一行不正确。请将其更改为
points(x.DENS.2, y.DENS.2$y)
这是完整的代码。它对我有用。因此,当您绘制结果时,检查输入的维度以确保它们匹配将非常有帮助。
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)