Published
Edited
Jun 5, 2021
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
data1 = {
var data = [
{ name: "foo", x: 10, y: 20 },
{ name: "bar", x: 50, y: 60 },
{ name: "stuff", x: 15, y: 75 },
{ name: "something really long", x: 80, y: 50 },
{ name: "something even longer akhdihfi", x: 40, y: 30 }
];
return data;
}
Insert cell
plot = {
const height = 100;
const width = 400;
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

// Add the rect elements, these are placeholders
svg
.append("g")
.selectAll("rect")
.data(data1)
.join("rect")
.attr("x", d => d.x)
.attr("y", d => d.y)
.style("fill", "black")
.style("opacity", "0.5");

// Add the text
svg
.append("g")
.style("font", "10px sans-serif")
.style("fill", "#000")
.selectAll("text")
.data(data1)
.join("text")
.attr("x", d => d.x)
.attr("y", d => d.y)
.text(d => d.name);

return Object.assign(svg.node(), {
update() {
svg.selectAll("text").each(function(d) {
d.bbox = this.getBBox();
console.log(d.bbox);
});

// Update the rectangles using the sizes we just added to the data
const xMargin = 4;
const yMargin = 2;
svg
.selectAll("rect")
.data(data1)
.join("rect")
.attr("width", d => d.bbox.width + 2 * xMargin)
.attr("height", d => d.bbox.height + 2 * yMargin)
.attr('transform', function(d) {
return `translate(-${xMargin}, -${d.bbox.height * 0.8 + yMargin})`;
});
}
});
}
Insert cell
plot.update()
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