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

时间:2015-11-30 11:42:32

标签: javascript d3.js charts linechart

我已经用D3.js创建了一个折线图,但似乎无法弄清楚如何完全控制X轴。

您可以看到我的示例:http://codepen.io/DesignMonkey/pen/KdOZNQ

我已经将x轴的刻度计数设置为3天,并且我有一个31天的数组,应该在x轴的每一端显示一天,并跳到每三天一次。但由于某种原因,当a轴在本月通过第1个时,它显示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)));

});

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

/彼得

更新:

我发现它想要展示新的一个月。请参阅此笔:http://codepen.io/DesignMonkey/pen/jbgYZx

它没有说" Septemper 1"但只有" Septemper"喜欢它想标记月份的变化。如何禁用此功能? :)

1 个答案:

答案 0 :(得分:2)

解决方案:

  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)

然后:

public MenuButton(Bitmap buttonImage)
   : base()
{
   this.Image = buttonImage
}

谢谢:)

相关问题