自定义时间轴

时间:2015-07-21 03:11:26

标签: d3.js

我希望我的x轴看起来像这样:

custom time axis

到现在为止我有这个:

http://jsfiddle.net/mer0c26h/

var margin = {top: 10, right: 10, bottom: 50, left: 30},
    width = 800 - margin.left - margin.right,
    height = 800 - margin.top - margin.bottom;
    padding = 30;

var svg = d3.select("#chart")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom);

var dataset = [
                [ new Date(2015,1,1), 800, new Date(2015,8,1), 0 ],
                [ new Date(2015,2,1), 800, new Date(2015,9,1), 0 ],
                [ new Date(2015,3,1), 800, new Date(2015,10,1), 0 ],
                [ new Date(2015,4,1), 800, new Date(2015,11,1), 0 ],
                [ new Date(2015,5,1), 800, new Date(2015,12,1), 0 ],
                [ new Date(2015,6,1), 800, new Date(2016,1,1), 0 ]
              ];

var min = d3.min(dataset, function(d) { return d[0]; });
var max = d3.max(dataset, function(d) { return d[2]; });
var monthformat = d3.time.format("%B");
var yearformat = d3.time.format("%Y");

var xScale = d3.time.scale()
    .domain([min, max])
    .range([0, width]);

var xAxis1 = d3.svg.axis()
    .scale(xScale)
    .tickFormat(monthformat)
    .tickSize(5,0)
    .orient("bottom");

var xAxis2 = d3.svg.axis()
    .scale(xScale)
    .ticks(d3.time.years, 1)
    .tickFormat(yearformat)
    .tickSize(5,0)
    .orient("bottom");

svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(20," + (height - padding) + ")")
  .call(xAxis1);

svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(20," + (height + 10) + ")")
    .call(xAxis2);

var year = 2015;
d3.selectAll("g.axis g.tick line")
 .attr("y2", function(d){
   if (year != d.getFullYear()) {
    return 15;
   }
   else {
    return 5;
   }
   year = d.getFullYear();
 });

但它还需要更多。

  • 可以在D3中执行此操作吗?
  • 你能给我一些提示吗?
  • 我可以使用类似的例子吗?

0 个答案:

没有答案