Skip to content Skip to sidebar Skip to footer

How To Set Y Axis (ydomain) Value To Max In D3 Js

In My D3 chart, How to set yDomain to the max value. Any suggestions ? If we see on nov 10 my line and area is going out of the box. My Code sandbox here I am calculating the tw

Solution 1:

There are several ways to calculate the yDomain in place. Yours does obviously work, it can be significantly simplified, though:

var yDomain = [
  d3.min(data, d =>Math.min(d.magnitude, d.startupMagnitude)),
  d3.max(data, d =>Math.max(d.magnitude, d.startupMagnitude))
];

This approach checks whatever value magnitude or startupMagnitude is smaller / greater using Math.min() / Math.max(), respectively, for any data point. It then utilizes d3.min() and d3.max() to calculate the global extent over those values.

Solution 2:

As you have a relational condition inside your function, it'll always take the larger value. You could instead calculate the two domains separately for startupMagnitude and magnitude, and then union the extents (take the minimum and maximum of the minimum and maximum extent values, respectively).

const magnitude = d3.extent(data, d => d.magnitude);
const startup = d3.extent(data, d => d.startupMagnitude);
const yDomain = [
    d3.min([magnitude[0], startup[0]]),
    d3.max([magnitude[1], startup[1]])
];

Or, a single-assignment version, exploiting that you just union the extents:

const yDomain = d3.extent([
    ...d3.extent(data, d => d.magnitude), 
    ...d3.extent(data, d => d.startupMagnitude)
]);

Yet another is to union the data first, then compute the extent:

const yDomain = d3.extent([
    ...data.map(d => d.magnitude), 
    ...data.map(d => d.startupMagnitude)
]);

These don't mix the D3 way of calculating min/max/extent with the different semantics of Math.min/Math.max, eg. handling of strings, nulls, and results if the array is empty. In this regard, the last version is the most faithful to the D3 way, as it uses a single d3.extent.

Solution 3:

This is how I am calculating the two domains separately for startupMagnitude and magnitude, and then comparing the max and min and creating the yDomain.

I am not sure this is correct or any other d3 method is there,

    var yDomainMagnitude = d3.extent(data, function(d) {
        return d.magnitude;
    });

    var yDomainStartupMagnitude = d3.extent(data, function(d) {
        return d.startupMagnitude;
    });

    var max =
        d3.max(d3.values(yDomainMagnitude)) >
        d3.max(d3.values(yDomainStartupMagnitude))
            ? d3.max(d3.values(yDomainMagnitude))
            : d3.max(d3.values(yDomainStartupMagnitude));
    var min =
        d3.min(d3.values(yDomainMagnitude)) <
        d3.min(d3.values(yDomainStartupMagnitude))
            ? d3.min(d3.values(yDomainMagnitude))
            : d3.min(d3.values(yDomainStartupMagnitude));
    var yDomain = [min, max];

Post a Comment for "How To Set Y Axis (ydomain) Value To Max In D3 Js"