如何用d3.js绘制散点图中的直线

时间:2013-07-01 14:37:53

标签: d3.js

我希望使用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

2 个答案:

答案 0 :(得分:6)

要在绘图中添加一行,您需要做的就是将一些行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路径元素。这对于线而言比一次绘制一个直线段更常见。文档为here.

另一方面,如果您将数据全部创建为一个对象,您可能会发现在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

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

答案 1 :(得分: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
    }
  }

}