Published
Edited
Apr 3, 2020
Insert cell
Insert cell
{
const svg = d3
.create('svg')
.attr('width', width)
.attr('height', width / 2);

const g = svg
.append('g')
.attr('transform', `translate(${width / 2},${width / 2 / 2})`);

const wc = wordCloud()
.width(width)
.height(width / 2);

g.datum(top(words, 100)).call(wc);

return svg.node();
}
Insert cell
top = (data, threshold) => data.filter((d, i) => i <= threshold)
Insert cell
wordCloud = () => {
let width = 400;
let height = 200;
let padding = 2;
let bubbles;

let r = d3
.scaleSqrt()
.range([0, 90])
.nice();

let x = d3.scaleLog().range([0, width]);

let s = d3.scaleSqrt().range([0, 2]);

const simulation = d3
.forceSimulation()
.velocityDecay(0.2)
.force("x", d3.forceX().strength(d => s(d.met)))
.force("y", d3.forceY().strength(d => s(d.met)))
.force(
"collide",
d3
.forceCollide()
.radius(function(d) {
return r(d.met) + padding;
})
.iterations(2)
)
// .force('r', d3.forceRadial(300))
.on("tick", () => {
bubbles.attr('transform', d => `translate(${d.x}, ${d.y})`);
});

function me(selection) {
selection
.attr("font-family", "sans-serif")
.attr("font-size", "10")
.attr("text-anchor", "middle");

r.domain([0, d3.max(selection.datum(), d => d.met)]);
x.domain([0.00001, d3.max(selection.datum(), d => d.met)]);

simulation.nodes(selection.datum());

bubbles = selection
.selectAll('g.bubble')
.data(selection.datum())
.join("g")
.attr('class', 'bubble')
.attr('transform', d => `translate(${d.x}, ${d.y})`);

bubbles
.append('circle')
.attr('r', d => r(d.met))
.attr('fill-opacity', 0.3)
.attr('fill', 'red')
.attr('stroke', 'red')
.attr('stroke-width', 1);

bubbles.append('text').text(d => d.word);
}

me.width = function(value) {
if (!arguments.length) {
return width;
}
width = value;
return me;
};

me.height = function(value) {
if (!arguments.length) {
return height;
}
height = value;
return me;
};

me.padding = function(value) {
if (!arguments.length) {
return padding;
}
padding = value;
return me;
};

return me;
}
Insert cell
_r = d3
.scaleSqrt()
.domain([0, d3.max(words, d => d.met)])
.range([0, 30])
.nice()
Insert cell
histogram = d3
.histogram()
.domain(_r.domain())
.thresholds(data => ss.ckmeans(data.map(d => d.met), 3).map(l => d3.min(l)))
.value(d => d.met)
Insert cell
bins = histogram(words)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
ss = require("simple-statistics@7")
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