D3.js折线图-用日期控制x轴

D3.js linechart - controlling x-axis with dates

本文关键字:控制 日期 js 折线图 D3      更新时间:2023-09-26

我用D3.js创建了一个折线图,但似乎不知道如何完全控制X轴。

你可以看到我的例子她:http://codepen.io/DesignMonkey/pen/KdOZNQ

我已经将x轴的蜱虫计数设置为3天,我有一个范围为31天的数组,它应该在x轴的每一端显示一天,并跳到第三天。但由于某种原因,当a轴通过本月的第一个时,它同时显示2015-08-31和2015-09-01,并没有像预期的那样跳到2015-09-03。

我的折线图代码在这里:

// Set the dimensions of the canvas / graph
let margin = {top: 30, right: 20, bottom: 30, left: 40},
    width = 330 - margin.left - margin.right,
    height = 180 - margin.top - margin.bottom;

// Set the ranges
var x = d3.time.scale().range([0, width]).nice(10);
var y = d3.scale.linear().rangeRound([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom")
    .ticks(d3.time.days, 3)
    .tickFormat(d3.time.format('%e'))
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10)
var yAxis = d3.svg.axis().scale(y)
    .orient("left")
    .ticks(5)
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10)
// Define the line
var valueline = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });
// Adds the svg canvas
let svg = d3.select(template.find(".chart"))
  .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 + ")");
// For each line 
data.forEach((item) => {
  // Scale the range of the data
  x.domain(d3.extent(item.data, function(d) {
    if(d.value != undefined)
      return d.date;
  }));
  // Create a perfect looking domainrange to the nearest 10th
  y.domain([
    Math.floor(d3.min(item.data, function(d) {
      if(d.value != undefined)
        return d.value;
    })/10)*10
    ,
    Math.ceil(d3.max(item.data, function(d) {
      if(d.value != undefined)
        return d.value;
    })/10)*10
  ]);
  // Add the X Axis
  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);
  // Add the Y Axis
  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);
  // Add only points that have value
  svg.append("path")
    .attr("class", "line color-"+ item.colorClass)
    .attr("d", valueline(item.data.filter((pnt) => pnt.value != undefined)));
});

有人能告诉我我在这里做错了什么吗?:)

/Peter

更新:

我发现这就像是,它想展示新的一个月。查看此笔:http://codepen.io/DesignMonkey/pen/jbgYZx

它没有说"September 1",只说"Septemper",就像它想给月份的变化贴上标签一样。如何禁用此功能?:)

解决方案:

var count = 0;
var tickRange = data[0].data.map((item) => {
  count = (count == 3) ? 0 : count+1;
  if(count == 1) {
   return item.date;
  }
})
.filter((d) => d != undefined);

然后:

  var xAxis = d3.svg.axis().scale(x)
      .orient("bottom")
      .ticks(d3.time.days, 3)
      .tickValues(tickRange)
      .tickFormat(d3.time.format('%e'))
      .innerTickSize(-height)
      .outerTickSize(0)
      .tickPadding(10)

感谢:)