Published
Edited
Nov 18, 2020
Insert cell
md`# D3 Bar Chart`
Insert cell
d3 = require('d3@5')
Insert cell
Insert cell
height = 500
Insert cell
width = 900
Insert cell
margin = ({
top: 10,
right: 10,
bottom: 20,
left: 35
})
Insert cell
yMax = d3.max(data, d => d.value)
Insert cell
xDomain = data.map(d => d.year)
Insert cell
xScale = d3.scaleBand()
.domain( xDomain )
.range([ margin.left, width - margin.right - margin.left ])
.padding(0.5)
Insert cell
yScale = d3.scaleLinear()
.domain([ 0, yMax ])
.range([ height - margin.bottom, margin.top ])
Insert cell
xAxis = d3.axisBottom(xScale)
.tickSizeOuter(0)
Insert cell
yAxis = d3.axisLeft(yScale)
.tickSizeOuter(0)
Insert cell
bars = {
const container = html `<svg width="900" height="500" />`
const svg = d3.select(container)
svg.append('g')
.attr('class', 'bars')
.selectAll('rect')
.data(data)
.join('rect')
.attr('class', 'bar')
.attr('x', d => xScale(d.year))
.attr('y', d => yScale(d.value))
.attr('width', xScale.bandwidth())
.attr('height', d => yScale(0) - yScale(d.value))
.style('fill', '#7472c0')
svg.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0,${ height - margin.bottom })`)
.call(xAxis)
svg.append('g')
.attr('class', 'y-axis')
.attr('transform', `translate(${ margin.left }, 0)`)
.call(yAxis)
return container

}
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