chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
svg
.append("g")
.call(xAxis)
.attr('transform', 'translate(10, 460)');
svg
.append("g")
.call(yAxis)
.attr('transform', 'translate(40, 0)');
svg.append("g");
const rectangles = svg
.selectAll()
.data(formatted_data)
.join(enter => enter.append("rect"))
.attr("x", d => x(+d.name))
.attr("y", d => {
if (d.value < 0) {
return y(0);
} else {
return y(d.value);
}
})
.transition()
.duration(1000)
.attr('width', (width - margin.left - margin.right) / 40)
.attr("height", d => Math.abs(y(0) - y(d.value)))
.attr("fill", d => color(d.key));
svg
.selectAll("rect")
.on("mouseover", function(d) {
d3.select(this).attr('fill-opacity', '1');
tooltip.style("visibility", "visible").html(`
<div>Year: ${d.target.__data__.name}</div>
<div>Album: ${cumulative_data.get(d.target.__data__.name).album}</div>
<div>Average Sentiment: ${Math.round(d.target.__data__.value * 1000) /
1000}</div>
`);
d3.select(this).attr('fill', '#eec42d');
})
.on("mousemove", function(e) {
tooltip
.style("top", e.pageY - 10 + "px")
.style("left", e.pageX + 10 + "px");
})
.on("mouseout", function() {
tooltip.style("visibility", "hidden");
d3.select(this)
.transition()
.attr('fill', d => color(d.key));
});
rectangles.selectAll('rect').on('click', function(d) {
d3.select(this)
.transition()
.attr('fill', d => color(d.key))
.attr('x', 250)
.attr('y', 250);
});
svg
.append("text")
.text("Years")
.style("font-size", "12px")
.attr("text-anchor", "middle")
.attr("transform", "translate(500, 600)");
svg
.append("text")
.text("Average Album Sentiment")
.style("font-size", "12px")
.attr("transform", "translate(10, 330) rotate(-90)");
svg
.append("text")
.text("Average Album Sentiment Across 40 years (1980 - 2019)")
.style("text-anchor", "middle")
.attr("transform", `translate(${width / 2}, 20)`)
.attr("font-weight", "bold")
.style("font-size", "20px");
return svg.node();
}