5

我正在寻找使用 d3.js 库实现 ggplot2 类型的图形以实现交互目的。我喜欢 ggplot2,但用户对交互式图表很感兴趣。我一直在探索 d3.js 库,似乎有很多不同的图形功能,但我真的没有看到任何统计图,如线性线、预测等。给定散点图,是否也可以将线性线添加到图形。

我有这个绘制散点图的示例脚本。如何在 d3.js 中向该图添加线性线?

// data that you want to plot, I've used separate arrays for x and y values
var xdata = [5, 10, 15, 20],
    ydata = [3, 17, 4, 6];

// size and margins for the chart
var margin = {top: 20, right: 15, bottom: 60, left: 60}
  , width = 960 - margin.left - margin.right
  , height = 500 - margin.top - margin.bottom;

// x and y scales, I've used linear here but there are other options
// the scales translate data values to pixel values for you
var x = d3.scale.linear()
          .domain([0, d3.max(xdata)])  // the range of the values to plot
          .range([ 0, width ]);        // the pixel range of the x-axis

var y = d3.scale.linear()
          .domain([0, d3.max(ydata)])
          .range([ height, 0 ]);

// the chart object, includes all margins
var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')

// the main object where the chart and axis will be drawn
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')   

// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');

main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');

main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);

// draw the graph object
var g = main.append("svg:g"); 

g.selectAll("scatter-dots")
  .data(ydata)  // using the values in the ydata array
  .enter().append("svg:circle")  // create a new circle for each value
      .attr("cy", function (d) { return y(d); } ) // translate y value to a pixel
      .attr("cx", function (d,i) { return x(xdata[i]); } ) // translate x value
      .attr("r", 10) // radius of circle
      .style("opacity", 0.6); // opacity of circle
4

2 回答 2

8

要在绘图中添加一条线,您需要做的就是将一些线 SVG 附加到您的主 SVG ( chart) 或包含您的 SVG 元素 ( main) 的组中。

您的代码如下所示:

chart.append('line')
    .attr('x1',x(10))
    .attr('x2',x(20))
    .attr('y1',y(5))
    .attr('y2',y(10))

这将画一条从 (10,5) 到 (20,10) 的线。您可以类似地为您的行创建一个数据集并附加一大堆。

您可能感兴趣的一件事是 SVG 路径元素。这对于线条来说比一次绘制一条直线更常见。文档在这里。

另一方面,如果将数据全部创建为一个对象,您可能会发现在 d3 中使用数据会更容易。例如,如果您的数据采用以下形式:

data = [{x: 5, y:3}, {x: 10, y:17}, {x: 15, y:4}, {x: 20, y:6}]

你可以使用:

g.selectAll("scatter-dots")
  .data(ydata)  // using the values in the ydata array
  .enter().append("svg:circle")  // create a new circle for each value
      .attr("cy", function (d) { return y(d.y); } ) //set y
      .attr("cx", function (d,i) { return x(d.x); } ) //set x

如果您的数据变得更复杂,这将消除潜在的混乱索引。

于 2013-07-01T15:18:57.487 回答
3

更新:这是相关的块:https ://bl.ocks.org/HarryStevens/be559bed98d662f69e68fc8a7e0ad097

我编写了这个函数来计算数据的线性回归,格式为 JSON。

它需要 5 个参数:1)您的数据 2)绘制在 x 轴上的数据的列名 3)绘制在 y 轴上的数据的列名 4)您的 x 轴的最小值 5) y 轴的最小值

我从http://classroom.synonym.com/calculate-trendline-2709.html得到了计算线性回归的公式

function calcLinear(data, x, y, minX, minY){
  /////////
  //SLOPE//
  /////////

  // Let n = the number of data points
  var n = data.length;

  var pts = [];
  data.forEach(function(d,i){
    var obj = {};
    obj.x = d[x];
    obj.y = d[y];
    obj.mult = obj.x*obj.y;
    pts.push(obj);
  });

  // Let a equal n times the summation of all x-values multiplied by their corresponding y-values
  // Let b equal the sum of all x-values times the sum of all y-values
  // Let c equal n times the sum of all squared x-values
  // Let d equal the squared sum of all x-values
  var sum = 0;
  var xSum = 0;
  var ySum = 0;
  var sumSq = 0;
  pts.forEach(function(pt){
    sum = sum + pt.mult;
    xSum = xSum + pt.x;
    ySum = ySum + pt.y;
    sumSq = sumSq + (pt.x * pt.x);
  });
  var a = sum * n;
  var b = xSum * ySum;
  var c = sumSq * n;
  var d = xSum * xSum;

  // Plug the values that you calculated for a, b, c, and d into the following equation to calculate the slope
  //  m = (a - b) / (c - d)
  var m = (a - b) / (c - d);

  /////////////
  //INTERCEPT//
  /////////////

  // Let e equal the sum of all y-values
  var e = ySum;

  // Let f equal the slope times the sum of all x-values
  var f = m * xSum;

  // Plug the values you have calculated for e and f into the following equation for the y-intercept
  // y-intercept = b = (e - f) / n = (14.5 - 10.5) / 3 = 1.3
  var b = (e - f) / n;

  // return an object of two points
  // each point is an object with an x and y coordinate
  return {
    ptA : {
      x: minX,
      y: m * minX + b
    },
    ptB : {
      y: minY,
      x: (minY - b) / m
    }
  }

}
于 2016-10-05T18:39:12.083 回答