d3 v4 scaleBand ticks

前端 未结 1 372
轮回少年
轮回少年 2020-12-15 13:08

I have data like the following

date,values
2016-10-01,10
2016-10-02,20
2016-10-03,30
2016-10-04,5
2016-10-05,50
2016-10-06,2
2016-10-07,7
2016-10-08,17

相关标签:
1条回答
  • 2020-12-15 13:33

    This can be done using tickValues indeed. For instance, in this demo, we have 200 values, so the axis is absolutely crowded:

    var svg = d3.select("body")
      .append("svg")
      .attr("width", 500)
      .attr("height", 100);
    
    var data = d3.range(200);
    
    var xScale = d3.scaleBand()
      .domain(data.map(function(d){ return d}))
      .range([10, 490]);
    
    var xAxis = d3.axisBottom(xScale);
    
    var gX = svg.append("g").call(xAxis);
    <script src="https://d3js.org/d3.v4.min.js"></script>

    Now, the same code using tickValues:

    var svg = d3.select("body")
      .append("svg")
      .attr("width", 500)
      .attr("height", 100);
    
    var data = d3.range(200);
    
    var xScale = d3.scaleBand()
      .domain(data.map(function(d){ return d}))
      .range([10, 490]);
    
    var xAxis = d3.axisBottom(xScale)
      .tickValues(xScale.domain().filter(function(d,i){ return !(i%10)}));
    
    var gX = svg.append("g").call(xAxis);
    <script src="https://d3js.org/d3.v4.min.js"></script>

    In this last snippet, tickValues uses the remainder operator to show only 1 in every 10 ticks:

    .tickValues(xScale.domain().filter(function(d,i){ 
        return !(i%10)
    }));
    
    0 讨论(0)
提交回复
热议问题