【问题标题】:plotting points on kernel density function unsuccessful in RR中核密度函数上的绘图点不成功
【发布时间】:2017-05-09 18:46:19
【问题描述】:

我试图在我的密度图上为seq(-3, 3) [即 7 个​​数字] 获取一些 points。我得到了 7 个相应的密度值,但是当我尝试执行 points 时,我得到:

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

由于确实没有长度差异,我假设在 x 和 y 之间存在 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 

【问题讨论】:

    标签: r class kernel-density probability-density density-plot


    【解决方案1】:

    y.DENS.2-object 实际上是一个包含 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")
    

    【讨论】:

      【解决方案2】:

      最后一行不正确。请改成

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

      【讨论】:

        猜你喜欢
        • 2015-09-12
        • 2012-06-09
        • 2014-10-08
        • 1970-01-01
        • 2014-12-19
        • 1970-01-01
        • 2015-12-26
        • 2018-01-23
        • 2020-10-29
        相关资源
        最近更新 更多