Published
Edited
Feb 13, 2021
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

svg.append("g").call(yGrid);

svg
.append("g")
.attr("fill", "steelblue")
.selectAll("rect")
.data(bins)
.join("rect")
.attr("x", d => xScale(d.x0) + barPadding) // position of each bar on xAxis, width adjustment (bar padding)
.attr("y", d => yScale(d.length))
.attr("width", d => d3.max([0, xScale(d.x1) - xScale(d.x0) - barPadding]))
.attr("height", d => yScale(0) - yScale(d.length));

svg.append("g").call(xAxis);

svg.append("g").call(yAxis);

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
width = 600
Insert cell
height = 500
Insert cell
margin = ({ top: 20, right: 20, bottom: 40, left: 40 })
Insert cell
barPadding = 1
Insert cell
Insert cell
bins = d3.bin().thresholds(40)(data)
Insert cell
bins.length
Insert cell
bins
Insert cell
bins[1][1]
Insert cell
Insert cell
xScale = d3
.scaleLinear()
.domain([bins[0].x0, bins[bins.length - 1].x1])
.range([margin.left, width - margin.right])
Insert cell
yScale = d3
.scaleLinear()
.domain([0, d3.max(bins, d => d.length)])
.nice()
.range([height - margin.bottom, margin.top])
Insert cell
Insert cell
xAxis = g =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(
d3
.axisBottom(xScale)
.ticks(width / 80)
.tickSizeOuter(0)
)
.call(g =>
g
.append("text")
.attr("x", width - margin.right)
.attr("y", -15)
.attr("fill", "currentColor")
.attr("font-weight", "bold")
.attr("text-anchor", "end")
.text(data.x)
)
Insert cell
yAxis = g =>
g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yScale).ticks(height / 40))
.call(g => g.select(".domain").remove())
Insert cell
Insert cell
yGrid = g =>
g
.selectAll('line')
.data(yScale.ticks())
.join('line')
.attr('x1', margin.left)
.attr('x2', width - margin.right)
.attr('y1', d => yScale(d))
.attr('y2', d => yScale(d))
.style("stroke-width", 0.2)
.style("stroke", "black")
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more