Public
Edited
Aug 29, 2023
2 forks
10 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3.selectAll('whatever')
.attr('width', (d) => d.value)
Insert cell
Insert cell
Insert cell
// Because the array contains objects rather than numbers, we'll need an accessor to let our functions know where to find the numbers. If we don't use an accessor, we won't get the result we're expecting.
data = [
{ name: 'a', value: 1 },
{ name: 'b', value: 2 },
{ name: 'c', value: 3 },
{ name: 'd', value: 5 },
{ name: 'e', value: 8 }
]
Insert cell
// Get the max value in the array
d3.max(data, (d) => d.value)
Insert cell
// Calculate the mean of the array
d3.mean(data, (d) => d.value)
Insert cell
// Accessors can be used to derive values from the original if we're not looking for a straight comparison
d3.max(data, (d) => Math.random() * d.value )
Insert cell
Insert cell
{
const data = [ 3, 2, 1 ]
d3.select(container)
.selectAll('rect').data( data )
.attr('foo', (d, i, arr) => {
console.log( 'd', d ) // 3, then 2, then 1
console.log( 'i', i ) // 0, then 1, then 2
console.log( 'arr', arr ) // [ rect, rect, rect ]
return i * 10
})
// run this block and look at your browser console to see the values logged
// Try changing the data array and see what happens
}
Insert cell
Insert cell
{
const svgHTML = html `<svg width="160" height="160" style="border: 1px solid #ccc" />`
const svg = d3.select( svgHTML )
const circles = svg.selectAll('circle').data( data )

circles.enter().append('circle')
// set the circles' radius
.attr('r', (d) => d.value * 10)
// set the circles' x position
.attr('cx', (d) => d.value * 10)
// set the circles' y position
.attr('cy', 80)
.attr('fill', 'transparent')
.attr('stroke', 'steelblue')
const text = svg.selectAll('text').data( data )
text.enter().append('text')
.attr('x', (d) => d.value * 10 * 2)
.attr('y', 80)
// This is a "magic number" in svg. It makes sure the text is vertically centered
.attr('dy', '0.35em')
// set from which direction the text expands
.attr('text-anchor', 'end')
// set the actual text
.text(d => d.name)

return svgHTML
}
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