问题
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