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

后端 未结 4 1580
猫巷女王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:14

    I ran into this problem when changing zoom levels on a bar chart with a time series based x-axis and found two solutions.

    1) Create a companion ordinal scale to help calculate the widths.(a pain)

    2) The time-series x axis is your friend - use it to calculate the width.

    If you want your bar to always be a "month" wide, irrespective of zoom level in you can do something like this. Im assuming d.date is available in the data.

     svg.selectAll(".air_used").attr("width", function(d.date) {
        var next = d3.time.month.offset(d.date, 1);
        return (x(next)- x(d));
      });
    

    This works well because it works for every zoom scale, and you just need to call this function at the end of your on "zoom" handler ie .on("zoom", zoomed); The x axis will usually have been adjusted at this point.

提交回复
热议问题