Public
Edited
Dec 15, 2021
7 forks
1 star
Insert cell
Insert cell
Insert cell
Insert cell
nestedDataJoin = {
const svg = d3.create("svg")
.attr("width", width)
.attr("height", 80);

// hierarchical data
const data = [
{ name: "a", arr: [1, 2, 3] },
{ name: "b", arr: [3, 2, 4] },
];
const groups = svg.selectAll("g").data(data).join("g");
groups.attr("transform", (d, i) => `translate(${i * 20 + 10},10)`);
// select all circles within each group and bind the inner array per data item
const circles = groups
.selectAll("circle")
.data((d) => d.arr)
.join("circle");
circles.attr("r", (d) => d * 2).attr("cy", (d, i) => i * 20);
return svg.node();
}
Insert cell
Insert cell
nestedSelection = {
const svg = d3.create("svg")
.attr("width", width)
.attr("height", 80);

const data = [1, 2, 3];
const circles = svg.selectAll("circle")
.data(data)
.join((enter) => {
const circles_enter = enter.append("circle").attr("r", 10);
// need to be separate since .append returns the appended element
circles_enter.append("title");
return circles_enter;
});
circles.attr("cx", (d, i) => d * 10).attr("cy", (d, i) => i * 50);
circles.select("title").text((d) => d);
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
chart = BarChart(data, {chartHeight: 350})
Insert cell
function BarChart(data, {
chartWidth = 800,
chartHeight = 600,
marginTop = 40,
marginBottom = 10,
marginLeft = 120,
marginRight = 20,
barHeight = 25
} = {}) {
const width = chartWidth - marginLeft - marginRight;
const height = chartHeight - marginTop - marginBottom;
// Creates sources <svg> element
const svg = d3.create("svg")
.attr('width', width + marginLeft + marginRight)
.attr('height', height + marginTop + marginBottom);

// Group used to enforce margin
const g = svg.append('g').attr('transform', `translate(${marginLeft},${marginTop})`);
// Render the chart with new data

// DATA JOIN use the key argument for ensurign that the same DOM element is bound to the same data-item
const rect = g.selectAll('rect').data(data).join(
// ENTER
// new elements
(enter) => enter.append('rect').attr('x', 0),
// UPDATE
// update existing elements
(update) => update,
// EXIT
// elements that aren't associated with data
(exit) => exit.remove()
);

// ENTER + UPDATE
// both old and new elements
rect
.attr('height', barHeight)
.attr('width', (d) => d * 7)
.attr('y', (d, i) => i * (barHeight + 5));
return svg.node();
}
Insert cell
<style>
rect {
fill: steelblue;
fill-opacity: 0.8;
}
rect:hover {
fill-opacity: 1;
}
.axis {
font-size: smaller;
}
</style>
Insert cell
data = [66.38, 21.51, 23.37, 34.17, 36.21]
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