0

How can I work out the extent of my domain using three different data dimensions? Consider the following data:

var data = [
  {
    "Date":"10-10-2013",
    "High1" : 3049,
    "High2" : 2100,
    "high3" : 43
  },
  {
    "Date":"09-10-2013",
     "High1" : 3142,
    "High2" : 2010,
    "high3" : 23
  },
  {
    "Date":"08-10-2013",
    "High1" : 3099,
    "High2" : 2190,
    "high3" : 90

  }

I want to plot a line for High1, another for High2 and another for High3 so need to find the extent of all combined so I can create a y axis for my graph.

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111

3 Answers3

5
var extents = ["High1", "High2", "high3"].map(function(dimensionName) {
    return d3.extent(data, function(d) { return d[dimensionName] });
});

var extent = [d3.min(extents, function(d) { return d[0] }),
              d3.max(extents, function(d) { return d[1] })];

This first calculates the extents for every dimension individually, then picks the global minimum and maximum.

ValarDohaeris
  • 6,064
  • 5
  • 31
  • 43
1

The trick is to use the accessors of d3.max and d3.min.

d3.max(data, function(d){
    return Math.max.apply(Math, [d.High1, d.High2, d.high3]);
})

d3.min(data, function(d){
    return Math.min.apply(Math, [d.High1, d.High2, d.high3]);
})

See here JavaScript: min & max Array values? if you don't understand the use of apply.

Community
  • 1
  • 1
RobinL
  • 11,009
  • 8
  • 48
  • 68
0

Building upon @ValarDohaeris answer, to make it slightly more generic and allowing for different numbers of series I've used this:

var extents = series.map(function(seriesName)
    {
        return d3.extent(data, function(d) { return d[seriesName]; });
    });

var yScale = d3.scaleLinear()
            .domain([d3.min(extents, function(d) { return d[0]; }),
                    d3.max(extents, function(d) { return d[1]; })])
            .range([height,0]);

where 'series' is the array containing the names of the series in the data. I'm using this in an angular directive to allow me to feed any number of series into a line graph

jTrouble
  • 68
  • 9