简体   繁体   English

D3时间尺度问题,计算项目位置

[英]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. 我正在使用在x轴上使用时间刻度的条形图。

Each bar represents a month so all the dates are setted as YYYY-MM and when I load the data i parse it with: 每个条形图代表一个月,因此所有日期都设置为YYYY-MM,当我加载数据时,我用以下方式对其进行解析:

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 在这里您可以找到代码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. 您有两种选择:对于x轴使用序数(类别)比例,这将使所有条形具有相同的宽度,或者根据月份的长度分别设置每个条形的宽度。

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. 要确定月份的长度,可以使用d3时间间隔来获取下个月开始的日期。 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. 然后,宽度就是xScale上两个日期位置之间的差,可以通过填充进行调整,以在小节之间留出一些空间。

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;
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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