d3.js路径不尊重域和范围

时间:2014-01-08 18:02:55

标签: d3.js

这里肯定有一些显而易见的东西。

我正在尝试画一条简单的线条,这是我的javascript:

// CRASH DATA 
var lineData = [ 
  { "x": 0,   "y": 0.5},
  { "x": 2,  "y": 0.1},
  { "x": 4,  "y": -0.5},
  { "x": 6,  "y": -0.8},
  { "x": 8,  "y": -0.9},
  { "x": 10, "y": -0.10},
  { "x": 12, "y": -0.10},
  { "x": 14, "y": -0.11},
  { "x": 16, "y": -0.10},
  { "x": 18, "y": -0.9},
  { "x": 20, "y": -0.7},
  { "x": 22, "y": -0.6},
  { "x": 24, "y": -0.5},
  { "x": 26, "y": -0.3},
  { "x": 28, "y": -0.1},
  { "x": 30, "y": 0.2},
  { "x": 32, "y": 0.4},
  { "x": 34, "y": 0.8},
  { "x": 36, "y": 0.8},
  { "x": 38, "y": 0.7},
  { "x": 40, "y": 0.4},
  { "x": 42, "y": 0.4},
  { "x": 44, "y": 0.4},
  { "x": 46, "y": 0.2},
  { "x": 48, "y": 0.1},
  { "x": 50, "y": 0}
];
//DRAW TRAJECTORY
function draw(data){
  var margin = {top: 30, right: 20, bottom: 30, left: 50},
      width = 600 - margin.left - margin.right,
      height = 270 - margin.top - margin.bottom;

  var x = d3.scale.linear().range([0, width]);
  var y = d3.scale.linear().range([height, 0]);

  var xAxis = d3.svg.axis().scale(x)
        .orient("bottom").ticks(5);

  var yAxis = d3.svg.axis().scale(y)
        .orient("left").ticks(5);

  //This is the accessor function we talked about above
  var lineFunction = d3.svg.line()
                           .x(function(d) { return d.x; })
                           .y(function(d) { return d.y; })
                           .interpolate("linear");

 var svg = d3.select("body")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  // Scale the range of the data
  x.domain(d3.extent(data, function(d) { return d.x; }));
  y.domain(d3.extent(data, function(d) { return d.y; }));

  svg.append("g")      // Add the X Axis
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  svg.append("g")      // Add the Y Axis
    .attr("class", "y axis")
    .call(yAxis);

  svg.append("path")   // Add the lineFunction path.
    .attr("class", "line")
    .attr("d", lineFunction(data));
};

//PUT EVERYTHING ON SCREEN
$( document ).ready(function() {
  draw(lineData);
});

结果如下:

Wrong path

1 个答案:

答案 0 :(得分:3)

您实际上并未使用您定义的音阶。你的行函数应该是

var lineFunction = d3.svg.line()
                       .x(function(d) { return x(d.x); })
                       .y(function(d) { return y(d.y); })
                       .interpolate("linear");

完整示例here