Published
Edited
Sep 29, 2022
5 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
sampleSvg = {
const dom = DOM.svg(width, height);

const svg = d3.select(dom);

svg
.append("rect")
.attr("width", width)
.attr("height", height)
.attr("fill", palette.bg);

const anchor = {
x:
textAnchor === "middle"
? width / 2
: textAnchor === "end"
? width - margin
: margin,
y: height / 2
};

svg
.append("circle")
.attr("cx", anchor.x)
.attr("cy", anchor.y)
.attr("r", 2)
.attr("fill", palette.debug);

svg
.append("text")
.datum(text) // Since only one data to bind. Use selectAll-data-join method if need binding of array.
// .selectAll("text")
// .data([text])
// .join("text")
.attr("x", anchor.x)
.attr("y", anchor.y)
.call(multilineText, {
fontFamily,
fontSize,
lineHeight,
textAnchor,
dominantBaseline
});

return dom;
}
Insert cell
function multilineText(
el,
{
fontFamily,
fontSize = 10,
lineHeight = 1.45,
textAnchor = "start",
dominantBaseline = "auto"
} = {}
) {
el.each(function (text) {
const lines = text.split("\n");
const textContentHeight = (lines.length - 1) * lineHeight * fontSize;

const el = d3.select(this);
const anchor = {
x: +el.attr("x"),
y: +el.attr("y")
};

const dy =
dominantBaseline === "middle"
? -textContentHeight / 2
: dominantBaseline === "hanging"
? -textContentHeight
: 0;

el.attr("font-family", fontFamily)
.attr("font-size", fontSize)
.attr("dominant-baseline", dominantBaseline)
.attr("text-anchor", textAnchor)
.selectAll("tspan")
.data(lines)
.join("tspan")
.text((d) => d)
.attr("x", anchor.x)
.attr("y", (d, i) => anchor.y + i * lineHeight * fontSize + dy);
});
}
Insert cell
palette = ({
bg: `hsl(0,0%,95%)`,
fg: `hsl(0,0%,5%)`,
debug: "#f0f"
})
Insert cell
fontFamily = `-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"`
Insert cell
margin = width / 20
Insert cell
width = 640
Insert cell
height = width / 1.6
Insert cell
Insert cell
Insert cell
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