简体   繁体   中英

D3 Issues with time scale, calculating the position of items

I am working on a bars chart that has uses a time scale on the x axis.

Each bar represents a month so all the dates are setted as YYYY-MM and when I load the data i parse it with:

var parseDate = d3.time.format("%Y-%m").parse;

The issue is that how each month has a different amount of days, the some bars are closer that others instead of having all the same margin, as you can see on this screenshot:

条形图

Here you can find the code, http://tributary.io/inlet/8700564

Thanks

You have two options: either use an ordinal (category) scale for the x-axis, which will give all the bars the same width, or set the width of each bar individually based on the length of the month.

To figure out the length of the month, you can use d3 time intervals to do get the date of the start of the next month. Then the width is just the difference between the two dates' positions on the xScale, possibly adjusted by padding to give some space between the bars.

rect.attr("x", function(d){return xScale(d.date) + padding;})
    .attr("width", function(d){
              return xScale( d3.time.month.offset(d.date, 1) )
                   - xScale(d.date)
                   - 2*padding;
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM