D3, dates on the x axis, data the width of a date

假装没事ソ 提交于 2019-12-25 05:36:11

问题


I am visualizing data by date. I want something a bit like this:

The point is that I want to draw rectangles that are the width of the days. Here's how I draw rectangles:

svg.selectAll(".my_class")
.data(my_data)
.enter()
.append("rect")
.attr({
    "width": function(d) { return x_scale.rangeBand(); },
    "height": function(d) { return h_scale(d.end - d.start); },
    "x": function(d) { return x_scale(new Date(d.date)); },
    "y": function(d) { return y_scale(d.end); },
    "class": function(d) { return d.device; }
});

The problem is that in order to get the right width, I ended up declaring my x_scale thus

d3.scale.ordinal()
.domain(my_data.map(function (d) { return new Date(d.date); }))
.rangeRoundBands([0, image_width]);

when I surely should have used d3.time.scale() instead. (Note the non-gaps after 2, 7, and 12 Feb.) The problem is that I don't see a way to specify the rectangle widths using d3.time.scale().

A work-around is to generate zero-height rectangles on the back end for every day in the period. This isn't that hideous, but I feel I should be able to do better. In addition, I'd lose niceties like .ticks(d3.time.weeks, 1) and have to spin them myself.

Any pointers?


回答1:


In the end, the simplest solution I found was to use an ordinal scale and provide (sometimes empty) elements for each date in the range.



来源:https://stackoverflow.com/questions/31112114/d3-dates-on-the-x-axis-data-the-width-of-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!