Public
Edited
Apr 29
Insert cell
Insert cell
Insert cell
Insert cell
data = d3.csvParse(await FileAttachment("CO2_emission.csv").text(), d3.autoType);
Insert cell
//Testing to ensure dataset is loaded properly
data[0]["Indicator Name"]

Insert cell
Insert cell
//get an array of all the years(manually created)
years = Array.from({ length: 2019 - 1990 + 1 }, (_, i) => 1990 + i);
Insert cell
/*map the emissions into an object with following structure:
{
name: _____,
code: ___,
region: _______,
emissions: [
{year: ___, value: ___},
{year: ___, value: ___},
{year: ___, value: ___},
...
],
}
*/
parsed = data.map(d => ({
name: d["Country Name"],
code: d.country_code,
region: d.Region,
emissions: years.map(year => ({
year: year,
value: +d[year] || null
}))
}));
Insert cell
//Function that gets emissions based on year: used in dot plots
function emissionsByYear(parsed, year) {
return parsed
.map(d => ({
name: d.name,
region: d.region,
value: d.emissions.find(e => e.year === year)?.value
}))
.filter(d => d.value !== null);
}
Insert cell
//Function to get total emissions for every region for every year
function stackData(){
let stackedData = [];

for (let year of years) {
//go one year at a time to calculate region totals
const regionalTotals = {};
for (let country of parsed) {
//calculate region totals by going through each country
const region = country.region
const value = country.emissions.find(e => e.year === year)?.value
if (value != null) {
if (!regionalTotals[region]) regionalTotals[region] = 0
regionalTotals[region] += value
}
}
for (let region of Object.keys(regionalTotals)) {
//add required info to stackedData for every region
stackedData.push({ year, region, value: regionalTotals[region] })
}
}
//return transformed data that is usable for stacked area map
return stackedData
}
Insert cell
stackedData = stackData() //store return value from function into variable
Insert cell
//Transform data to a format that makes creating parallel coordinate plots easy
parallelData = parsed.map(d => {
const obj = { name: d.name, region: d.region }
for (let e of d.emissions) {
obj[e.year] = e.value
}
return obj
})

Insert cell
Insert cell
Insert cell
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