Published
Edited
Aug 21, 2019
2 forks
6 stars
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
// append clipping mask for sliding behavior
svg.append('defs').append('clipPath')
.attr('id', 'barGroup_clip')
.append('rect')
.attr('transform', `translate(${margin.left}, ${margin.top})`)
.attr('width', width - margin.left - margin.right)
.attr('height', height - margin.top - margin.bottom);

svg.append("g")
.attr('id', 'barGroup')
.attr("fill", "steelblue")
.style('clip-path', 'url(#barGroup_clip)')
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d, i) => margin.left + (barWidth + 3) * i)
.attr("y", d => y(d.value))
.attr("height", d => y(0) - y(d.value))
.attr("width", barWidth);

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

svg.append("g")
.call(yAxis);
const anchorIdx = Math.round((width - margin.left - margin.right) / (barWidth + 3)) - 1;
const brushGroup = svg.append('g')
.attr('class', 'brush')
.attr('transform', `translate(${margin.left}, ${height - margin.bottom})`)
.call(brush)
.call(brush.move, [0, x2(data[anchorIdx].name)]);
brushGroup.selectAll('rect').attr('height', brushHeight);

return svg.node();
}
Insert cell
data = (await d3.csv("https://gist.githubusercontent.com/mbostock/81aa27912ad9b1ed577016797a780b2c/raw/3a807eb0cbb0f5904053ac2f9edf765e2f87a2f5/alphabet.csv", ({letter, frequency}) => ({name: letter, value: +frequency}))).sort((a, b) => b.value - a.value)
Insert cell
barWidth = 50
Insert cell
brushHeight = 30
Insert cell
x = d3.scaleBand()
.domain(data.map(d => d.name))
.range([margin.left, width - margin.right])
.padding(0.1);
Insert cell
x2 = d3.scaleBand()
.domain(x.domain())
.range([margin.left, width - margin.right])
Insert cell
brushed = () => {
const s = d3.event.selection || x2.range();
d3.select('#barGroup')
.attr('transform', `translate(${-s[0]}, 0)`)
}
Insert cell
brush = d3.brushX()
.extent([[0, 0], [width - margin.right - margin.left, brushHeight]])
.on('brush end', brushed);
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0).tickValues([]))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
Insert cell
height = 300
Insert cell
margin = ({top: 20, right: 0, bottom: 100, left: 40})
Insert cell
d3 = require("d3@5")
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