TMoore TMoore - 19 days ago 6
JSON Question

d3.js graphing sub arrays from JSON

So I am attempting to draw a simple line graph. The path to the arrays are fairly long, It seems the forEach function is not looping through the array? Am I missing a function to successfully create d.date which comes out as 'null' and d.air which comes out as 'NaN'?

data[0].STATION[0].OBSERVATIONS.date_time, and data[0].STATION[0].OBSERVATIONS.air_temp_set_1 are the arrays I want to plot

Here it is on blockbuilder:
http://blockbuilder.org/TMoore24/b9906fd3893034b91f13e0c86acb2f75

Many thanks!

Answer

There are two things going on here.

(1):

data.forEach(function(d) {
    d.date = format(data[0].STATION[0].OBSERVATIONS.date_time);
    d.air = +data[0].STATION[0].OBSERVATIONS.air_temp_set_1;
});

These don't work because both data[0].STATION[0].OBSERVATIONS.date_time, and data[0].STATION[0].OBSERVATIONS.air_temp_set_1 are arrays.

What you probably want is this.

var obs = data[0].STATION[0].OBSERVATIONS;
var dates = obs.date_time.map(format);
var air = obs.air_temp_set_1.map(function(d){ return +d; });

data.date = dates;
data.air = air;

What this leaves you with is an array of dates and and array of air temps.

Unfortunately, this leads to issue #2.

(2)

var line = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.air); });

This function assumes that each object, d, takes the form {date: SINGLE_DATE_VALUE, air: SINGLE_NUMERIC_VALUE, etc} but what you actually have is data = {date:[ARRAY_OF_DATES, air: ARRAY_OF_TEMPERATURES, etc...}

To use the line function above, then you need to create an array of objects of the form {date: DATE_VALUE, air: AIR_TEMPERATURE_VALUE}. There are various ways you can do that depending on how you want your final data structured. Here's one way:

data.airTempByDate = data.date.map(function(d, i){
    return {
        date: d,
        air: air[i]
    };
});

Hope this makes sense! Here's a working block on blockbuilder with the fixes above.

Comments