Public
Edited
Aug 29, 2023
12 forks
31 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
d3.select('#myId') // select by id
d3.select('.my-id') // select by class
d3.select('#containerId rect.my-rectangle') // select children elements that match a class, etc.
return 'These selectors all work'
}
Insert cell
Insert cell
html `<svg height="40" width="40" style="border:1px solid #ccc"/>`
Insert cell
Insert cell
oneShape = {
const svgHTML = html `<svg height="40" width="40" style="border:1px solid #ccc"/>`
// first, we select our svg object
const svg = d3.select(svgHTML)
// now, we append a rect (rectangle) element to the SVG
const rect = svg.append('rect')
// finally, we style and position the rect
rect
.style('fill', 'black') // rect's fill color
.attr('height', 20) // rect's height (in pixels)
.attr('width', 20) // rect's width (in pixels)
.attr('x', 10) // x position of the top-left corner
.attr('y', 10) // y position of the top-left corner
return svgHTML
}
Insert cell
Insert cell
Insert cell
Insert cell
html `<svg height="40" width="160" style="border: 1px solid #ccc" />`
Insert cell
Insert cell
{
const svgHTML = html `<svg height="40" width="160" style="border: 1px solid #ccc" />`
// Select our svg element just like before
const svg = d3.select(svgHTML)

// Now, select all rects that are contained by the svg
const rects = svg.selectAll('rect')

// Define the data that we will bind to our rectangles
// each element in the array will become a new rect
const data = [ 0, 1, 2, 3, 4 ]
rects
// The data join - the big moment!
// When we do this, we tell D3 to include
// 5 additional rects in our selection, one for each element in our data array
.data( data )
// Now we append the rects just like before.
// Unlike before, when we append, we're actually
// appending all 5 rects at once
.join('rect')
// ...and when we set style and attributes, we're setting them
// for all 5 rects at once, too
.style('fill', 'black')
.attr('height', 20)
.attr('width', 20)
.attr('y', 10)
// This positions each new rect 10 pixels to the right
// of the last rect. We'll explain what's going on here on day 3
.attr('x', (d,i) => { return 10 + (i * 30) })
return svgHTML
}
Insert cell
Insert cell
Insert cell
d3 = require('d3@6')
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