Skip to content

Instantly share code, notes, and snippets.

@russelllim22
Last active December 3, 2021 20:49
Show Gist options
  • Save russelllim22/2779c4572b9ff329e9154363cc7acc77 to your computer and use it in GitHub Desktop.
Save russelllim22/2779c4572b9ff329e9154363cc7acc77 to your computer and use it in GitHub Desktop.
const chartSVG = d3.select("#chartSVG")
const yScale = d3.scaleBand()
.domain(letterCounts.map(d => d.letter))
.range([0, 3200]) // my chart is 3200px high
.paddingInner(0.1)
.paddingOuter(0.1);
const xScale = d3.scaleLinear()
.domain([0,450000]) // the most popular letter (A) has about 450000 babies
.range([0,1600 - 150]) // my chart is 1600px wide (minus 150px for the label)
chartSVG.selectAll(".bar")
.data(letterCounts)
.join("rect")
.classed("bar",true)
.attr("fill", "white")
.attr("stroke","black")
.attr("x", 0)
.attr("y", d => yScale(d.letter))
.attr("height", yScale.bandwidth())
.attr("width", d => xScale(d.count));
chartSVG.selectAll(".label")
.data(letterCounts)
.join("text")
.classed("label",true)
.text(d => `${d.letter}: ${Math.round(100*d.count/totalBabies)}%` + (d.letter === "other" ? ` (${d.otherLetters.slice(0,-1)})`: ""))
.style("font-size",35)
.style("font-weight", 700)
.attr("fill", "black")
.attr("stroke","none")
.attr("x", d => xScale(d.count) + 10)
.attr("y", d => yScale(d.letter) + yScale.bandwidth() / 2 + 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment