如何在D3中生成每年的轴刻度线?

时间:2016-09-22 21:59:37

标签: d3.js axis

如何在D3中生成每年的刻度?

以下代码似乎适用于我的数据跨越多年,但它显示数据只有几年(比如3年)的几个月?

// Store a value in the array, at index (posX, posY, posZ), only if
// that position in the array is currently empty
function storeDateNoOverride(theArray, posX, posY, posZ, date) {
    var theArray = theArray || [];
    theArray[posX] = theArray[posX] || [];
    theArray[posX][posY] = theArray[posX][posY] || [];
    theArray[posX][posY][posZ] = theArray[posX][posY][posZ] || date;
}

// If variable theArray doesn't have a value yet, assign it to a new array
var theArray = theArray || [];

storeDateNoOverride(theArray, 30, 1, 0, new Date());

1 个答案:

答案 0 :(得分:5)

您可以使用轴生成器中的tickFormat显式设置刻度线格式::

xAxis.tickFormat(d3.timeFormat("%Y"));

检查片段,第一个轴从2000年到2016年,第二个轴从2014年到2016年。第三个是相同的,但ticks(d3.timeYear)每年仅保留1个刻度:



var width = 400, height = 200;

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

var xAxisScale1 = d3.scaleTime()
    .domain([new Date(2000, 0, 1), new Date(2016, 0, 1)])
    .rangeRound([20,width - 20]);

var xAxisScale2 = d3.scaleTime()
    .domain([new Date(2014, 0, 1), new Date(2016, 0, 1, 0)])
    .rangeRound([20,width - 20]);

var xAxis1 = d3.axisBottom(xAxisScale1);

var xAxis2 = d3.axisBottom(xAxisScale2).tickFormat(d3.timeFormat("%Y"));

svg.append("g").call(xAxis1);

svg.append("g").attr("transform", "translate(0,40)").call(xAxis2);

svg.append("g").attr("transform", "translate(0,80)").call(xAxis2.ticks(d3.timeYear));

<script src="https://d3js.org/d3.v4.min.js"></script>
&#13;
&#13;
&#13;