Published
Edited
Mar 14, 2021
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
let maxTotal=0;
nestedData.forEach(function(yearGroup) {
//for each entry in the nested array, each of which contains all the rows for a given year,
//calculate the total count, and the before-and-after counts for each category (species).

yearGroup.year = +yearGroup.key;

yearGroup.bars = [];
//create an array to hold one value for each bar

var total = 0; //total count per date

yearGroup.values.forEach(function(row) {
//the values array created by the nest function
//contians all the original row data objects
//that match this year (i.e., the nesting key)

//create an object representing the bar for
//the Lutra_lutra count, and add to the bars array
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Lutra_lutra",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Lutra_lutra) //new total
}
);

//create an object representing the bar for
//the Not_identified count, and add to the bars array
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Not_identified",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Not_identified) //new total
}
);
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Unsure",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Unsure) //new total
}
);
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Multiple",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Multiple) //new total
}
);
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Aonyx_cinereus",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Aonyx_cinereus) //new total
}
);
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Lutrogale_perspicillata",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Lutrogale_perspicillata) //new total
}
);
yearGroup.bars.push(
{
year:+row.Year,
sum: +row.Sum,
species: "Lutra_sumatrana",
use: row.Use,
y0: total, //total value *before* this bar
y1: (total = total + +row.Lutra_sumatrana) //new total
}
);
});

maxTotal = Math.max(maxTotal, total); //update max

});
return [maxTotal, nestedData]

}
Insert cell
console.log(data)
Insert cell
parser = d3.timeParse("%Y")
Insert cell
xScale = d3.scaleLinear().domain([1980,2020]).range([margin.left, width - margin.right])
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more