Skip to content

Instantly share code, notes, and snippets.

@russelllim22
Last active December 3, 2021 21:20
Show Gist options
  • Save russelllim22/5f6cd43b96312bdc7afd711f489a1614 to your computer and use it in GitHub Desktop.
Save russelllim22/5f6cd43b96312bdc7afd711f489a1614 to your computer and use it in GitHub Desktop.
// Adapted from https://observablehq.com/@pixnwave/word-cloud-with-counts
function makeCloud(letter, width) {
const words = [...letterNames[letter]].filter(d=>d.size>99); // only render names with at least 100 babies
const height = yScale.bandwidth();
const cat10 = ["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"];
var layout = d3.layout.cloud()
.size([width + 10, height])
.words(words)
.padding(2)
.rotate(d => d.rotate | 0)
.fontSize(d => 0.5*Math.sqrt(d.size))
.on("end", draw);
layout.start();
function draw(words) {
chartSVG.append("g")
.attr("width", width)
.attr("height", height)
.attr("transform", d=> `translate(${width/2},${yScale(letter) + height/2})`)
.style("text-anchor", "middle")
.selectAll("text")
.data(words)
.enter()
.append("text")
.style("font-size", d => `${d.size}px`)
.attr("transform", d => `translate(${[d.x, d.y]})rotate(${d.rotate})`)
.attr("fill", (d,i) => cat10[Math.floor(Math.random()*10)])
.text(d => d.text);
}
}
// Each word cloud takes some time to be rendered,
// so I used a setTimeout to render them one by one.
for(let i=0; i<letterCounts.length; i++){
setTimeout(()=>{
makeCloud(letterCounts[i].letter, xScale(letterCounts[i].count))
},500*i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment