chart = {
let svg, xAxis, yAxis, title;
if (!this) {
svg = d3
.create("svg")
.attr("width", width)
.attr("height", height);
xAxis = svg
.append("g")
.attr("class", "xaxis")
.attr("transform", `translate(0,${height - margin.bottom})`);
yAxis = svg
.append("g")
.attr("class", "yaxis")
.attr("transform", `translate(${margin.left},0)`);
title = svg
.append("text")
.attr("class", "chart_title")
.attr("transform", `translate(${width / 2},15)`)
.style("text-anchor", "middle");
}
else {
svg = d3.select(this);
xAxis = svg.select(".xaxis");
yAxis = svg.select(".yaxis");
title = svg.select(".chart_title");
}
xAxis
.transition()
.duration(500)
.call(d3.axisBottom(xScale).tickFormat(d3.format(".0%")));
yAxis.call(d3.axisLeft(yScale).tickFormat(customTickFormatter));
title.text(`Percentage of people in ${state} living in each income bracket`);
const rects = svg.selectAll("rect").data(data, d => d.group);
rects.join(
enter =>
enter
.append("rect")
.attr("x", xScale.range()[0])
.attr("y", d => yScale(d.group))
.attr("height", d => yScale.bandwidth())
.attr("width", d => {
return xScale(d.pct) - xScale.range()[0];
}),
update =>
update
.transition()
.duration(500)
.delay((d, i) => i * 200)
.attr("width", d => xScale(d.pct) - xScale.range()[0]),
exit => exit.remove()
);
return svg.node();
}