chart = {
let svg, g_x_axis, g_y_axis, title, xlabel, ylabel;
if (!this) {
svg = d3
.create("svg")
.attr('width', width)
.attr('height', height);
g_x_axis = svg
.append("g")
.attr("class", "xaxis")
.attr("transform", `translate(0, ${height - margin.bottom})`);
g_y_axis = svg
.append("g")
.attr("class", "yaxis")
.attr("transform", `translate(${margin.left}, ${margin.bottom})`);
title = svg
.append("text")
.attr("class", "title")
.attr("x", width / 2)
.attr("y", margin.top / 3)
.style("text-anchor", "middle");
xlabel = svg
.append("text")
.attr("class", "xlabel")
.attr("x", width / 2)
.attr("y", height - margin.bottom / 3)
.style("text-anchor", "middle")
.text("Year");
ylabel = svg
.append("text")
.attr("transform", "rotate(-90)")
.attr("class", "ylabel")
.attr("x", -height / 2)
.attr("y", margin.left / 4)
.style("text-anchor", "middle")
.text("Population (number of residents)");
} else {
svg = d3.select(this);
g_x_axis = svg.select(".xaxis");
g_y_axis = svg.select(".yaxis");
title = svg.select(".title");
}
g_y_axis
.transition()
.duration(500)
.call(y_axis);
g_x_axis.call(x_axis);
title.text(`Population of ${state}`);
const bars = svg.selectAll('rect').data(data, d => d[x_variable]);
bars.join(
enter =>
enter
.append("rect")
.attr("x", d => x_scale(d[x_variable]))
.attr("width", x_scale.bandwidth() - 1)
.attr("y", d => y_scale(d[y_variable]) + margin.bottom - 1)
.attr(
"height",
d => height - margin.bottom - margin.top - y_scale(d[y_variable])
)
.attr("fill", d => color_scale(d[color_variable])),
update =>
update.call(g =>
g
.transition()
.duration(1000)
.attr("y", d => y_scale(d[y_variable]) + margin.bottom)
.attr(
"height",
d => height - margin.bottom - margin.top - y_scale(d[y_variable])
)
.attr("fill", d => color_scale(d[color_variable]))
),
exit => exit.remove()
);
return svg.node();
}