x轴上的数据条应正确对齐

时间:2019-06-25 05:55:15

标签: d3.js charts

我正在使用d3.js v5构建我的第一个条形图,我想要的是条形图应在x轴上正确对齐

我几乎已经完成了图表的构建,但是无法找出问题所在

var headingOne;
var headingTwo;
var dataset;
var description;
var frequency;
var barPadding = 20;

document.addEventListener("DOMContentLoaded", function() {
  var req = new XMLHttpRequest(); // Next time will use d3.json();
  req.open(
    "GET",
    "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/GDP-data.json",
    true
  );
  req.send();
  req.onload = function() {
    let json = JSON.parse(req.responseText);
    headingOne = json.source_name;
    headingTwo = `From ${json.from_date.substring(0,4)} to ${json.to_date.substring(0,4)}`;
    dataset = json.data;
    descripton = json.description;

    d3
      .select("body")
      .append("h1")
      .text(headingOne)
      .attr("class", "headings")
      .attr("id", "title");

    d3
      .select("body")
      .append("h2")
      .text(headingTwo)
      .attr("class", "headings");

    var margin = { top: 20, right: 20, bottom: 50, left: 40 },
      height = 600 - margin.top - margin.bottom,
      width = 1100 - margin.left - margin.right;

    var minDate = new Date(dataset[0][0]);
    var maxDate = new Date(dataset[dataset.length - 1][0]);

    var xScale = d3.scaleTime().domain([minDate, maxDate]).range([barPadding, width - barPadding]);
    var yScale = d3.scaleLinear().domain([0, d3.max(dataset, d => d[1])]).range([height, barPadding]);

    var xAxis = d3.axisBottom().scale(xScale);
    var yAxis = d3.axisLeft().scale(yScale);

    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 + ")");

    svg.selectAll("rect")
    .data(dataset)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("x", (d, i) => i * (width / dataset.length))
    .attr("data-date", (d) => d[0])
    .attr("y", (d) => yScale(d[1]))
    .attr("data-gdp", (d) => d[1])
    .attr("width", width / dataset.length)
    .attr("height", d => height - yScale(d[1]))





    svg.append("g").attr("transform", "translate("+barPadding+"," + (height) + ")").attr("id", "x-axis").call(xAxis);

    svg.append("g").attr("transform", "translate("+margin.left+", 0)").attr("id", "y-axis").call(yAxis);


  };

});

我希望这些条在x轴上正确对齐。 现在,条形图在x轴(x轴的开始向左)的起点之前开始,这是错误的,但在右侧位置(x轴的向右终点)结束了 数据已超出限制。

0 个答案:

没有答案