在d3中约束轴标签

时间:2016-07-23 20:38:16

标签: d3.js

我正在学习教程,所以我可以学习一些d3js。

这是我的代码:

DWORD

结果如下:

graph

数据是:

'use strict';
//Dashboard

//setup size of line chart
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;

//parse data from file
var parseDate = d3.time.format("%b").parse;

//set scales
var x = d3.time.scale()
     .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

//create axes
 var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

//construct the line using points from data
var line = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.users); });

var svg = d3.select(".linechart").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 + ")");

d3.tsv("data.tsv", function(error, data) {
  if (error) throw error;
//traverse through the data 
    data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.users = +d.users;
  });
//establish the domain for x and y axes
  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain(d3.extent(data, function(d) { return d.users; }));

//add "groups" 
  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Users (unique)");

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

我的问题是关于轴,如何强制它不在x轴上插入不在数据集中的标签?

1 个答案:

答案 0 :(得分:2)

手动设置x轴的刻度:

...
if (error) throw error;

var ticks = data.map(function(d) { return parseDate(d.date) };
...
x.domain(d3.extent(data, function(d) { return d.date; })).tickValues(ticks);

https://github.com/d3/d3-3.x-api-reference/blob/master/SVG-Axes.md#tickValues