将边界线添加到D3折线图

时间:2020-03-24 01:59:21

标签: d3.js

如何将水平边界线添加到d3.js折线图中? 例如。如果边界是4.5披萨,我们想在图表上显示4.5是y轴边界。是svg.append的方法,用于添加1个额外的“网格”类型的线(它实际上不是图形的一部分)。

const genData = () => {
  var listDate = [];
  var startDate ='2017-02-01';
  var endDate = '2017-02-10';
  var dateMove = new Date(startDate);
  var strDate = startDate;
  while (strDate < endDate){
    var strDate = dateMove.toISOString().slice(0,10);
    listDate.push({date: strDate, pizzas: Math.floor((Math.random() * 5000) + 1000)});
    dateMove.setDate(dateMove.getDate()+1);
};
  return listDate;
}

let data = genData();

console.log("data: ", data);

// Calculate Margins and canvas dimensions
var margin = {top: 40, right: 40, bottom: 40, left: 60},
    width = 700 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

//Parsers and Formaters
//var parseTime = d3.timeParse("%d/%m/%Y");
var parseTime = d3.timeParse("%Y-%m-%d");
var formatTime = d3.timeFormat("%a/%b/%Y");

// Scales
var x = d3.scaleTime() // x scale (is given to x-axis below)
    .range([0, width]);

var y = d3.scaleLinear() // y scale (is given to y-axis below)
    .range([height, 0]);

// Line generator
var line = d3.line()
    .x(function(d) { return x(this.parseTime(d.date)); }) // x values for line
    .y(function(d) { return y(d.pizzas/1000); }) // y values for line
    .curve(d3.curveMonotoneX) // apply smoothing

var svg = d3.select("body").append("svg")
    .style("background-color", '#888')
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

 //Arguments for axes : Ranges for X, y  

 x.domain(d3.extent(data, function(d) { return parseTime(d.date); })); // input of x scale (range is output)
 y.domain(d3.extent(data, function(d) { return d.pizzas/1000; })); // input of y scale

// Axes
  svg.append("g")
      .attr("class", "axis axis--x")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(d3.axisLeft(y));
  // Labels
  svg.append("text")
            .attr("text-anchor", "middle")
            .style("font-size", "14px")
            .attr("transform", "translate("+ (margin.left - 94 ) +","+(height/2)+")rotate(-90)")  
            .text("Pizzas ( Thousands ) ");

  svg.append("text")
            .style("font-size", "14px")
            .attr("text-anchor", "middle") 
            .attr("transform", "translate("+ (width/2) +","+(height-(margin.bottom -74))+")")
            .text("Date");

// Data Lines:

   svg.append("path")
       .datum(data)
      .attr("class", "line")
      .attr("d", line);

(请参阅this codepen。)

0 个答案:

没有答案