D3.js: calculate width of bars in time scale with changing range?

后端 未结 4 1554
猫巷女王i
猫巷女王i 2020-12-29 03:37

I\'m building a D3 bar chart with a time scale on the x-axis. The range of the x-axis can vary.

How can I specify the correct width for the bars on the bar chart? I

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-29 04:02

    There's no function to get the width, but you can calculate it quite easily:

    .attr("width", width/data.length);
    

    You might want to subtract a small amount from that if you don't want the bars to touch. You would also need to adjust the x position accordingly, e.g.

    .attr("x", function(d) { return x(d.date) - (width/data.length)/2; })
    .attr("width", width/data.length);
    

    To get the ticks to align properly, you'll also need to adjust the range of the x axis scale because the first tick will be placed at the first value:

    var x = d3.time.scale().range([width/data.length/2, width-width/data.length/2]);
    

    Complete jsfiddle here.

提交回复
热议问题