{
let months = {}
for(let i = 0; i<monarchs.length;i++){
let sightingMonth;
if (parseInt(monarchs[i].month) < 10){
sightingMonth = monarchs[i].year + "0" + monarchs[i].month;
}
else{
sightingMonth = monarchs[i].year + monarchs[i].month;
}
if (sightingMonth in months){
months[sightingMonth]++
}
else {
months[sightingMonth] = 1;
}
}
let butterfliesByMonth = [];
for (let property in months) {
butterfliesByMonth.push(
{name:property, count:months[property]}
)
}
//sort months by their name - weird and not covered in the tutorial, but should make some intuitive sense?
//looks like an accessor function, right?
butterfliesByMonth.sort((a, b) => {
return parseInt(a.name) - parseInt(b.name);
});
//svg variables
let width = 800;
let height = 400;
let margin = 25;
//create SVG artboard
let svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("width",width)
.attr("height",height)
.attr("fill","#ddd")
//create SVG background
let bg = svg.append("rect")
.attr('x',0)
.attr('y',0)
.attr("width",width)
.attr("height",height)
//accessor function to find min and max counts
let monthMinMax = d3.extent(butterfliesByMonth, d => d.count);
//scales for counts to pixels and parameters
let monthSizeScale = d3.scaleLinear().domain(monthMinMax).range([margin,height-(margin*2)]);
let monthParameterScale = d3.scaleLinear().domain(monthMinMax).range([0,1]);
//how wide should each bar be?
let barWidth = (width - (margin * 2)) / butterfliesByMonth.length;
//loop through all items in dataset
for (let i = 0; i < butterfliesByMonth.length; i++){
// for converting data to pixels
let barLength = monthSizeScale(parseFloat(butterfliesByMonth[i].count))
// for converting data to parameter between 0 and 1
let barParameter = monthParameterScale(parseFloat(butterfliesByMonth[i].count))
//draw rectangle for each month
svg.append("rect")
.attr("x", (i*barWidth) + margin)
//pesky needing to flip vertically
.attr("y", (height - barLength) - margin)
.attr('width', barWidth)
.attr('height', barLength)
.attr('fill', d3.interpolatePlasma( barParameter))
//check if we are seeing a January...
if ( butterfliesByMonth[i]["name"].slice(4) == "01"){
//add a textlabel for the new year
svg.append("text")
.attr("x", (i*barWidth) + margin)
.attr("y", height - (margin/2))
.text( butterfliesByMonth[i]["name"].slice(0,4) )
.attr('fill','black')
.attr('font-family','courier')
.attr('font-size',8)
}
}
//show visualization in Observable
return svg.node();
}