Public
Edited
Aug 29, 2023
12 forks
Importers
26 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
colors = d3.scaleOrdinal(
data.categories,
d3.schemeGnBu[9].slice(3)
)
Insert cell
xScale = d3.scaleBand(
data.map(d => d.location),
[ margin.left, width - margin.right ]
).padding(0.2)
Insert cell
yScale = d3.scaleLinear(
[ 0, d3.max(data, d => d.total) ],
[ height - margin.bottom, margin.top ]
)
Insert cell
xAxis = d3.axisBottom(xScale)
.tickSizeOuter(0)
Insert cell
yAxis = d3.axisLeft(yScale)
Insert cell
Insert cell
stack = d3.stack()
.keys( data.categories )
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = {

const svg = d3.create('svg')
.attr('width', 900)
.attr('height', 500)

// Pass our data to the stack to generate the layer positions
const chartData = stack( data )
const groups = svg.append('g')
// Each layer of the stack goes in a group
// the group contains that layer for all countries
.selectAll('g')
.data( chartData )
.join('g')
// rects in the same layer will all have the same color, so we can put it on the group
// we can use the key on the layer's array to set the color
.style('fill', (d,i) => colors(d.key))
groups.selectAll('rect')
// Now we place the rects, which are the children of the layer array
.data(d => d)
.join('rect')
.attr('x', d => xScale(d.data.location))
.attr('y', d => yScale(d[1]))
.attr('height', d => yScale(d[0]) - yScale(d[1]))
.attr('width', xScale.bandwidth())

svg.append('g')
.attr('transform', `translate(0,${ height - margin.bottom })`)
.call(xAxis)
svg.append('g')
.attr('transform', `translate(${ margin.left },0)`)
.call(yAxis)
.select('.domain').remove()

return svg.node()
}
Insert cell
Insert cell
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