X轴标签(日期)未正确送达D3 v4

时间:2018-06-26 06:59:21

标签: javascript d3.js

我正在使用d3 v4版本制作折线图。 X轴标签是日期(仅年份)。 X轴标签贴不正确。

它彼此重叠。我只想在x轴标签中显示年份。我尝试使用d3.timeparse值仍然不正确。

帮我知道问题所在。

codepen链接-https://codepen.io/pinkisharma/pen/oyPzWW

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}

</style>
<body>

<!-- load the d3.js library -->     
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
    initLineChart();
    function initLineChart(){
        // set the dimensions and margins of the graph
        var margin = {top: 20, right: 40, bottom: 30, left: 50},
            width = 450 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

        // parse the date / time
        var parseTime = d3.timeParse("%Y");
        var data =[{"date":"2014","EPS":"34.13","EBITDA":"34.12"},{"date":"2015","EPS":"63.98","EBITDA":"45.56"},{"date":"2016","EPS":"67.00","EBITDA":"54.00"},
                  {"date":"2017","EPS":"45.00","EBITDA":"22.17"},{"date":"2018","EPS":"18.32","EBITDA":"24.13"}];
        // set the ranges
        var x = d3.scaleTime().range([0, width]);
        var y = d3.scaleLinear().range([height, 0]);


        // define the 1st line
        var valueline = d3.line()
            .x(function(d) { return x(d.date); })
            .y(function(d) { return y(d.EBITDA); });

        // define the 2nd line
        var valueline2 = d3.line()
            .x(function(d) { return x(d.date); })
            .y(function(d) { return y(d.EPS); });

        // append the svg obgect to the body of the page
        // appends a 'group' element to 'svg'
        // moves the 'group' element to the top left margin
        var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
            .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
            .append("g")
            .attr("transform",
                  "translate(" + margin.left + "," + margin.top + ")");

        // Get the data
          // format the data
          data.forEach(function(d) {
              d.date = parseTime(d.date);
              d.EBITDA = +d.EBITDA;
              d.EPS = +d.EPS;
          });

          // Scale the range of the data
          x.domain(d3.extent(data, function(d) { return d.date; }));
          y.domain([0, d3.max(data, function(d) {
              return Math.max(d.EBITDA, d.EPS); })]);

          // Add the valueline path.
          svg.append("path")
              .data([data])
              .attr("class", "line")
              .style("stroke", "#00357F")
              .style("fill", "none")
              .style("stroke-width", "3px")
              .attr("d", valueline);

          // Add the valueline2 path.
          svg.append("path")
              .data([data])
              .attr("class", "line")
              .style("stroke", "#006600")
              .style("fill", "none")
              .style("stroke-width", "3px")
              .attr("d", valueline2);

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

          // Add the Y Axis
          svg.append("g")
              .call(d3.axisLeft(y));
         // Add the scatterplot
          svg.selectAll("dot")
              .data(data)
              .enter().append("circle")
              .attr("r", 5)
              .style("fill", "#00357F")
              .attr("cx", function(d) { return x(d.date); })
              .attr("cy", function(d) { return y(d.EBITDA); });
        // Add the scatterplot
          svg.selectAll("dot")
              .data(data)
              .enter().append("circle")
              .attr("r", 5)
              .style("fill", "#006600")
              .attr("cx", function(d) { return x(d.date); })
              .attr("cy", function(d) { return y(d.EPS); });


    }

</script>
</body>

1 个答案:

答案 0 :(得分:1)

您可以使用.ticks(n)来提示轴渲染器大概绘制的刻度数。由于您希望每年显示一次价格变动,因此您可以尝试使用n 1 来计算年数,而不必自己尝试手动计算d3.timeYear.every(1)的值。

p / s:附加提示:由于您只关心显示年份,因此您可能还想使用.tickFormat()来确保仅显示年份:

svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x).tickFormat(d3.timeFormat("%Y")).ticks(d3.timeYear.every(1)));

initLineChart();

function initLineChart() {
  // set the dimensions and margins of the graph
  var margin = {
      top: 20,
      right: 40,
      bottom: 30,
      left: 50
    },
    width = 450 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

  // parse the date / time
  var parseTime = d3.timeParse("%Y");
  var data = [{
      "date": "2014",
      "EPS": "34.13",
      "EBITDA": "34.12"
    }, {
      "date": "2015",
      "EPS": "63.98",
      "EBITDA": "45.56"
    }, {
      "date": "2016",
      "EPS": "67.00",
      "EBITDA": "54.00"
    },
    {
      "date": "2017",
      "EPS": "45.00",
      "EBITDA": "22.17"
    }, {
      "date": "2018",
      "EPS": "18.32",
      "EBITDA": "24.13"
    }
  ];
  // set the ranges
  var x = d3.scaleTime().range([0, width]);
  var y = d3.scaleLinear().range([height, 0]);


  // define the 1st line
  var valueline = d3.line()
    .x(function(d) {
      return x(d.date);
    })
    .y(function(d) {
      return y(d.EBITDA);
    });

  // define the 2nd line
  var valueline2 = d3.line()
    .x(function(d) {
      return x(d.date);
    })
    .y(function(d) {
      return y(d.EPS);
    });

  // append the svg obgect to the body of the page
  // appends a 'group' element to 'svg'
  // moves the 'group' element to the top left margin
  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
    .append("g")
    .attr("transform",
      "translate(" + margin.left + "," + margin.top + ")");

  // Get the data
  // format the data
  data.forEach(function(d) {
    d.date = parseTime(d.date);
    d.EBITDA = +d.EBITDA;
    d.EPS = +d.EPS;
  });

  // Scale the range of the data
  x.domain(d3.extent(data, function(d) {
    return d.date;
  }));
  y.domain([0, d3.max(data, function(d) {
    return Math.max(d.EBITDA, d.EPS);
  })]);

  // Add the valueline path.
  svg.append("path")
    .data([data])
    .attr("class", "line")
    .style("stroke", "#00357F")
    .style("fill", "none")
    .style("stroke-width", "3px")
    .attr("d", valueline);

  // Add the valueline2 path.
  svg.append("path")
    .data([data])
    .attr("class", "line")
    .style("stroke", "#006600")
    .style("fill", "none")
    .style("stroke-width", "3px")
    .attr("d", valueline2);

  // Add the X Axis
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x).tickFormat(d3.timeFormat("%Y")).ticks(d3.timeYear.every(1)));

  // Add the Y Axis
  svg.append("g")
    .call(d3.axisLeft(y));
  // Add the scatterplot
  svg.selectAll("dot")
    .data(data)
    .enter().append("circle")
    .attr("r", 5)
    .style("fill", "#00357F")
    .attr("cx", function(d) {
      return x(d.date);
    })
    .attr("cy", function(d) {
      return y(d.EBITDA);
    });
  // Add the scatterplot
  svg.selectAll("dot")
    .data(data)
    .enter().append("circle")
    .attr("r", 5)
    .style("fill", "#006600")
    .attr("cx", function(d) {
      return x(d.date);
    })
    .attr("cy", function(d) {
      return y(d.EPS);
    });


}
.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

脚注:

  1. 查看d3.timeYear()interval.every()的用法