使用 d3 和 numericjs 在 javascript 中绘制错误椭圆

Drawing an error ellipse in javascript with d3 and numericjs

我正在尝试实现 this 在 javascript 中绘制协方差误差椭圆的方法。

errorEllipse = function(stdDevX, stdDevY, cor, center, level) {
  var errEllipse,
  cov = cor * stdDevX * stdDevY,
  covmat = [
  [stdDevX * stdDevX, cov],
  [cov, stdDevY * stdDevY]
  ],
  eig = numeric.eig(covmat),
  scale = Math.sqrt(jStat.chisquare.inv(level, 2)),
  maxLambdaI = indexOfMax(eig.lambda.x),
  minLambdaI = indexOfMin(eig.lambda.x),
  rx = stdDevX > stdDevY ? Math.sqrt(eig.lambda.x[maxLambdaI]) * scale : Math.sqrt(eig.lambda.x[minLambdaI]) * scale,
  ry = stdDevY > stdDevX ? Math.sqrt(eig.lambda.x[maxLambdaI]) * scale : Math.sqrt(eig.lambda.x[minLambdaI]) * scale,
  v1 = eig.E.x[maxLambdaI],
  theta = Math.atan2(v1[1], v1[0]) * 180 / Math.PI;

  if (theta < 0) {
    theta += 360;
  }
  //make the ellipse object
  errEllipse = {
    rx: rx,
    ry: ry,
    cx: center.x,
    cy: center.y,
    orient: -theta
  };

  return errEllipse;
};

我在当前尝试的结果中看到的最明显的问题是椭圆不适合数据。很难准确找到我哪里出错了。

谁能告诉我: 1.) 我如何获取或绘制椭圆的半径和角度有什么问题。 要么 2.) javascript 中绘制错误/置信省略号的任何示例。

我正在使用 numericjs 库来获取特征向量和值,使用 jstat 和 d3 来绘图。

Here is a plnkr 与当前代码。

errorEllipse函数在“script.js”file.Test数据可以通过编辑testData.js来改变。

更新:

我正在添加用 d3 绘制椭圆的代码,以防出现问题:

svg.append('ellipse')
  .attr('class', 'q-ellipse-99')
  .attr('rx', Math.abs(xScale(xExtent[0] + ellipse99.rx) - xScale(xExtent[0])))
  .attr('ry', Math.abs(yScale(yExtent[0] + ellipse99.ry) - yScale(yExtent[0])))
  .attr('transform', 'translate(' + xScale(ellipse99.cx) + ',' + yScale(ellipse99.cy) + ')rotate(' + ellipse99.orient + ')');

xExtent 和 yExtent 数组都是通过对数据调用 d3.extent() 返回的。

最初的问题是我在绘图时没有缩放椭圆的 rx 和 ry 值。现在似乎可以使用上面的代码(正在更新)。这是一个 fork of plnkr,它使用随机正常测试数据(如下)代替。

function genTestData(numPoints){
  var data = {x:[], y:[]};
  for(var i = 0; i < numPoints; i++){
    data.x[i] = jStat.normal.inv(Math.random(), 8.5, 2);
    data.y[i] = jStat.normal.inv(Math.random(), 6.5, 3);
    data.y[i] += data.x[i] * 2.1; //to test ellipse
  }
  return data;
}