Public
Edited
Jan 26, 2023
Insert cell
Insert cell
svg = {
const height = 200;
const width = 200;

const margin = {
top: 10,
right: 0,
bottom: 0,
left: 30
};

const yScale = d3
.scaleLinear()
.range([height - margin.bottom, margin.top])
.domain(d3.extent(data, (d) => d.value));

const svg = d3
.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto; height: intrinsic;")
.attr("font-family", "sans-serif")
.attr("font-size", 10);

const g = svg
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);

const text = g
.selectAll(".name")
.data(data)
.join("text")
.attr("class", "name")
.attr("x", 20)
.attr("y", (d) => yScale(d.value))
.attr("fill", "#454545")
.text((d) => `${d.name} - ${d.value}`);
// .call(wrap, 500);

d3.selectAll(".name").each(function (d) {
d3.select(this).call(wrap, 100);
});

return svg.node();
}
Insert cell
data = [
{ name: "Family in feud with Zuckerbergs", value: 17 },
{ name: "Committed 671 birthdays to memory", value: 19 },
{ name: "Ex is doing too well", value: 10 },
{ name: "High school friends all dead now", value: 15 },
{ name: "Discovered how to “like” things mentally", value: 27 },
{ name: "Not enough politics", value: 12 }
]
Insert cell
function wrap(text, width) {
console.log(text, width);
text.each(function () {
const text = d3.select(this);
console.log(text);
const words = text.text().split(/\s+/).reverse();
console.log(words);
let word = "";
let line = [];
const lineHeight = 1.1; // ems
const x = text.attr("x");
let tspan = text.text(null).append("tspan").attr("x", x);
while ((word = words.pop())) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text
.append("tspan")
.attr("x", x)
.attr("dy", lineHeight + "em")
.text(word);
}
}
});

const breaks = text.selectAll("tspan").size();
console.log(breaks);
text.attr("y", function () {
return +text.attr("y") + -6 * (breaks - 1);
});
}
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