18

This is a problem that I have previously solved using php or (what I thought was) needlessly complex MySQL queries, but which I suddenly thought there must be a more elegant solution in JavaScript / d3.js.

Imagine I have a data set of dates and values that I want to convert into a bar chart in d3.js.

date,value
2013-01,53
2013-02,165
2013-03,269
2013-04,344
2013-05,376
2013-06,410
2013-07,421
2013-09,376
2013-10,359
2013-11,392
2013-12,433
2014-01,455
2014-02,478

You will notice that there is no entry for the 8th month (August) in the data. The assumption is that August is a zero value and the end result being that the resulting bar chart looks normal, but of course there is no 8th month where it should be a gap (zero).

enter image description here

enter image description here

I have a jsfiddle of the script and data here for reference.

I considered trying to add a complete data set populated with zeros and then iterating over it to include values from the data, but that seems overly complicated as well. I am making the assumption that there is an elegant solution that I'm just too ignorant to know.

Thanks for your help.

Edit #1: in response to the answer from explunit:

The solution should ideally be a manipulation of the data series as opposed to being applicable to just a bar graph. This would mean that the equivalent of the line graph at this jsfiddle would have a sudden dip in the middle of it.

Edit #2: After a bit of playing about:

After having a play with the suggestions on the Google groups page here, I have managed to get a piece of code to do what I was looking for . It takes the time stamp data, creates a domain based on the time range and creates a separate array with separate months (in this case). Then I crudely iterate through both arrays set and add the values appropriate for the initial (not fully populated with time values) array into the array with all the time values (and data values initially set to zero).

The end result is a line graph which would initially look like this because it iterates between July and September 2013;

enter image description here

Subsequently being rendered as this because the August value would be added as zero;

enter image description here

There is a jsfiddle of the code here;

I'll be first to say it. While it is accomplishing the job I'm wanting in this instance, it is a long way from elegant or extensible. If someone cleverer than I is able to see how this could be made less offensive, I would be grateful.

4
  • Hi d3noob! I enjoy your very useful book. So, are you saying that you want a gap...like this or not? I am not clear on this...sorry. Apr 22, 2014 at 19:50
  • It must be that you don't have the luxury of knowing that data is missing for a particular data point...thus the reference zero-filled data that you mentioned...well, will let you interject when you are available :) Apr 22, 2014 at 20:03
  • Thanks Fern. You're right about the gap and right about not having the luxury of knowing the data doesn't have a zero value associated with a time stamp. I'll explore explunit's answer below and see if that fits the bill. It looks good at first glance :-).
    – d3noob
    Apr 23, 2014 at 5:43
  • In fact searching on the topic now using the assumption that what I'm trying to do is make a quantitative scale act like an ordinal scale. It would seem like there's a thread on google groups that threw up some ideas as well. groups.google.com/forum/#!topic/d3-js/7GsDmnB4kdE
    – d3noob
    Apr 23, 2014 at 7:48

3 Answers 3

11

I've not greatly improved on your overall approach, but if you use some more built-in methods and add underscore/lodash you can make the data transformation a lot shorter:

x.domain(d3.extent(data, function(d) { return d.date; })).ticks(d3.time.month);
y.domain([0, d3.max(data, function(d) { return d.value; })]);

var newData = x.ticks().map(function(monthBucket) {
    return _.find(data, {date: monthBucket}) || {date: monthBucket, value: 0};
});

If we tell it that it should use monthly ticks, then we can just get the ticks array back out again rather than constructing a separate buckets array.

And then from that point we just use .map rather than for loop and lodash (or underscore) _.find method to match up to our original data. Updated fiddle here: http://jsfiddle.net/a5jUz/3/


Original answer below... in case you want to use D3 scales to spread out the values on bar graph:

1 - You have to use a time scale rather than an ordinal scale:

var x = d3.time.scale().range([0, width]);

2 - You need to set the domain of that scale based on the min/max of the date range:

x.domain(d3.extent(data, function(d) { return d.date; })).nice();

3 - [the ugly part] now that you're not using ordinal scale, you don't have the rangeBand function for the bar positioning:

  // TODO: calculate based on overall width & number of data points  
  .attr("x", function(d) { return x(d.date); })
  .attr("width", 16)

Updated fiddle here: http://jsfiddle.net/LWyjf/

7
  • Thanks for what IS a clever solution that I think could work for a bar graph with a bit of fiddling with the code. Nice effort.
    – d3noob
    Apr 23, 2014 at 5:55
  • However... the solution that I'm aiming for (and I should have articulated it better sorry) would actually introduce the zero value into the data. I might be asking a bit too much and I could almost be accused of moving the goal posts, but in the ideal world, the solution would be applicable to the bar graph above AND the equivalent line graph per this fiddle (jsfiddle.net/4kdm4). I will add some more description to the question. Thanks for the answer though!
    – d3noob
    Apr 23, 2014 at 6:02
  • @d3noob added code sample & fiddle based on your clarification
    – explunit
    Apr 24, 2014 at 2:53
  • Woah! That looks almost too good to be true! I will need a day or so to try and understand the code, but what I see there looks really clever! Nice job!
    – d3noob
    Apr 24, 2014 at 8:12
  • OK, it's official. That rocks. I have never come across Lo-Dash or Underscore before, so that's really clever for a start and using the ticks function to equally space the values in the array is masterful. Nice. Many thanks. I will be writing up a section for the book D3 Tips and Tricks and including a longer breakdown of the technique (which, with your permission I will call 'The explunit method'. If you are interested in reviewing the section, drop me a line at the email address in the front of the book (Introduction section)
    – d3noob
    Apr 24, 2014 at 20:49
6

Here is another option for padding zeros without using lodash/underscore by using the d3.get() as opposed to _.find(). Not sure how this impacts performance though.

var date_range = d3.time.hours(startDate, endDate, 1);

var m = d3.map(data, function(d) { return d.date });
var newData = date_range.map(function(bucket) {
    return m.get(bucket) || {date: bucket, value: 0};
});
3

To improve on @explunit 's answer I prefer padding the zeros prior to mapping the data to the domain range so that you get the full dataset which won't affected by changes in scale to the domain:

var date_range = d3.time.days(minX, maxX, 1);
var newData = date_range.map(function(dayBucket) {
    return _.find(data, function(d) {
        return d.date = dayBucket;
    } || {date: dayBucket, value: 0};
});

and then

x.domain(d3.extent(newData, function(d) { return d.date; })).ticks(d3.time.day);
y.domain([0, d3.max(newData, function(d) { return d.value; })]);

etc.

I'll update the JSFiddle and post here soon.

3
  • Thanks @greenafrican, That is a nice solution and I can see me using it in the future. I like the fact that it does not require the lodash library (not that lodash isn't awesome). Both the answers here have been excellent.
    – d3noob
    Jan 14, 2015 at 17:45
  • It does actually use the lodash library _.find as @explunit 's answer does :) Jan 15, 2015 at 7:55
  • Please pardon my lack of attention. So it does.
    – d3noob
    Jan 15, 2015 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.