我试图在points
[即7个数字]的密度图上获得一些seq(-3, 3)
。我得到了7个相应的密度值但是当我尝试执行points
时,我得到:
Error in xy.coords(x, y) : 'x' and 'y' lengths differ
实际上没有长度差异,我假设x和class()
之间存在points()
差异问题。
我很欣赏解决方案吗?
以下是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
答案 0 :(得分:0)
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")
答案 1 :(得分:0)
最后一行不正确。请将其更改为
分(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)