Public
Edited
Feb 15, 2024
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
basic_workflow = {
const svg = d3.create("svg")
.attr("width", width)
.attr("height", 120);

const data = [1, 2, 3];
// select svg element
// select all circles - even if there none yet - and bind the data array `data` onto them
// call .join to specify the data binding / joining
const circles = svg.selectAll("circle")
.data(data)
.join(
(enter) => {
// append an element matching the selector and set constant attributes
const circles_enter = enter.append("circle");
circles_enter.attr("r", 10);
circles_enter.attr("fill", "hsl(216deg 100% 13%)");
return circles_enter;
},
// update existing elements
(update) => update,
(exit) => {
// exit phase
return exit.remove();
}
);
// update phase ... actually update all including the newly created ones
// function argument given two parameters:
// 1. argument (common name: d): the current data item
// 2. argument (common name: i): the index of the data item in the data array
// this context: the current DOM element
circles.attr("cx", (d, i) => d * 10);
circles.attr("cy", (d, i) => i * 50);
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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

// ENTER + UPDATE
// both old and new elements
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