Skip to content Skip to sidebar Skip to footer

Logarithmic Range

I have a very sparse dataset and I want to plot it in a histogram with a logarithmic scale. I would like the X axis to look something similar to: [1, 10, 100, 1000, 10000] Meaning

Solution 1:

A d3 Threshold Scale splits a quantitive dataset into discrete categories based on threshold points that you choose.

Unlike simple linear scales, the domain of the the threshold scale is not the min and max values. Instead, the threshold scale's domain is the list of threshold values at which you want to split your data.

As with all d3 scales, the range is the desired output values. For a threshold scale, however, the number of output values in the range has to be equal to the number of threshold (domain) values plus one. The first value in the range is assigned to values that are less than the first threshold, the second value in the range is assigned to values that are equal to or greater than the first threshold but less than the second, and so on, until the last value in the range is assigned to values that are equal to or greater than the last value in the domain.

So to split an array of positive integers into categories based on powers of 10, you could use the powers of 10 as your domain, and a set of strings describing the categories as your range:

scale = d3.scale.threshold()
          .domain([1, 11, 101, 1001, 10001])
          .range(["<1", "1-10", "11-100", "101-1000", "1001-10,000", ">10,001"]);

Of course, depending on what you are using the scale for, a custom function like @Daniele Torino suggested may be more versatile, since it doesn't require you to specify max and min threshold above/below which everything gets bunched in the same category. But if that is what you want, the threshold scale above should do it.

Solution 2:

If you are just looking for a function that maps your values, all you need is some simple math:

functionf(x) {
  returnMath.pow(10, Math.floor(Math.log(x) / Math.log(10)));
}

alert( f(1) );
alert( f(23) );
alert( f(2) );
alert( f(105) );
alert( f(2000) );
alert( f(30000) );

I have no experience with d3 so I cannot help you there.

Post a Comment for "Logarithmic Range"