Published
Edited
May 13, 2020
2 forks
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-extent[0])/(extent[1]-extent[0]),
})));}
Insert cell
extent = d3.extent(wordcounts, d => 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([1000, 500])
.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

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more