d3.js数据未在x轴上正确绘制

时间:2016-07-15 15:31:03

标签: d3.js

我正在学习d3并尝试实现特定的功能。 数据未正确绘制。我无法找到它出错的地方。

链接到jsfiddle https://jsfiddle.net/4nc1nc95/1/

    $(function() {
  var width = 355;
  var height = 142;
  var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 70
  };
  var scope = {
    graphData: {
      "data": [{
        "YEAR": "FY16Q1",
        "SAVINGS": null,
        "SPEND": null
      }, {
        "YEAR": "FY16Q2",
        "SAVINGS": null,
        "SPEND": null
      }, {
        "YEAR": "FY16Q3",
        "SAVINGS": null,
        "SPEND": null
      }, {
        "YEAR": "FY16Q4",
        "SAVINGS": "0.023961",
        "SPEND": "7419879.04"
      }, {
        "YEAR": "FY17Q1",
        "SAVINGS": "0.00618",
        "SPEND": "34923499.71732"
      }]
    }
  };

  var x_domain = d3.extent(scope.graphData.data, function(d) {
    return d.YEAR;
  });

  var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .0)
    .domain(scope.graphData.data.map(function(d) {
      return d.YEAR;
    }));

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

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

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

  var area = d3.svg.area()
    .x(function(d) {
      return x(d.YEAR);
    })
    .y0(height)
    .y1(function(d) {
      return y(d.SAVINGS);
    });

  var sampleSVG = d3.select('#area')
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + 62)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + (margin.top + 24) + ")");

  sampleSVG.append("path")
    .datum(scope.graphData.data)
    .attr("class", "area")
    .attr("d", area);


  sampleSVG.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  sampleSVG.append("g")
    .attr("class", "y axis")
    .call(yAxis);
  if (scope.mode == "restore") {
    sampleSVG.append("g")
      .append("text")
      .attr("y", "-8%")
      .attr("x", "-2%")
      .attr("class", "heading tableHeader")
      .text("SAVING");
  }
})

1 个答案:

答案 0 :(得分:0)

而不是:

var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .0)

使用:

var x = d3.scale.ordinal()
.rangePoints([0, width], .0)

这是你的小提琴:https://jsfiddle.net/gerardofurtado/b1mzyxLq/