Published
Edited
May 6, 2020
1 star
Insert cell
md`# Word Cloud (Why We Sleep by Matthew Walker)`
Insert cell
data = {return{series:wordcounts}}
Insert cell
chart = { const word_info = data.series; return makecloud(
word_info.map(d => ({text: d.name,
size: d.value,
fill: d.value,
})));}
Insert cell
d3 = require("d3")
Insert cell
cloud = require("d3-cloud")
Insert cell
// Adapted from https://github.com/jasondavies/d3-cloud/blob/master/examples/browserify.js
function makecloud(words) {
var a = DOM.svg();
var color_scale = d3.scaleSequential(d3.interpolateRainbow);
var layout = cloud()
.size([560, 370])
.words(words)
.padding(3)
.rotate(d => ~~(Math.random() * 1) * 90)
.font("Impact")
.fontSize(d => 15*Math.log(d.size))
.on("end", draw);

layout.start();

function draw(words) {
d3.select(a)
.attr("width", layout.size()[0])
.attr("height", layout.size()[1])
.append("g")
.attr(
"transform",
"translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")"
)
.selectAll("text")
.data(words)
.enter()
.append("text")
.style("font-size", d => `${d.size}px`)
.style("font-family", "Impact")
.attr("text-anchor", "middle")
.attr("transform", d => `translate(${[d.x, d.y]})rotate(${d.rotate})`)
.attr("fill", d => color_scale((Math.log(d.fill))))
.text(d => d.text);
}

return a;
}
Insert cell
wordcounts = [{'name': 'I', 'value': 25}, {'name': 'like', 'value': 42}, {'name': 'the', 'value': 26}, {'name': 'taste', 'value': 76}, {'name': 'of', 'value': 69}, {'name': 'this', 'value': 37}, {'name': 'restaurant', 'value': 25}]
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more