Published
Edited
Jun 12, 2020
Insert cell
Insert cell
random = d3.randomNormal(.5, .1)
Insert cell
scaleBandX = d3
.scaleBand()
.domain(Array.from({ length: data.length }).map((_, i) => i))
.range([0, width])
.paddingInner(20)
Insert cell
trans = (x, y) => `translate(${x},${y})`
Insert cell
scaleY = d3.scaleLinear().domain([d3.min(data), d3.max(data)])
// no range
Insert cell
scaleY(50)
Insert cell
fullscreen = {
const button = html`<button>redraw`;
button.onclick = () => chart.render(getData());
return button;
}
Insert cell
chart = {
const svg = d3
.create('svg')
.attr('height', 200)
.attr('width', width);

const updateBarPos = bar =>
bar
.transition()
.attr('transform', (d, i) =>
trans(scaleBandX(i), scaleY.range([200, 0])(d))
)
.attr('height', scaleY.range([0, 200]));

const enterBar = bar =>
bar
.append('rect')
.attr('class', 'bar')
.attr('width', scaleBandX.step())
.call(updateBarPos);

const updateBar = bar => bar.call(updateBarPos);

function render(_data) {
svg
.selectAll('.bar')
.data(_data, (d, i) => i)
.join(enterBar, updateBar, bar => bar.remove());
}

render(data);

return Object.assign(svg.node(), { render });
}
Insert cell
tryout = 500
Insert cell
dataSize = 100
Insert cell
dataMax = 200
Insert cell
getData = () => {
const _data = Array.from({ length: tryout }).map((_, i) =>
Math.floor(random(i) * dataSize)
)
const ary = Array.from({ length: dataSize }).map(() => 0);
_data.forEach(d => (ary[d] += 1));
return ary;
}
Insert cell
data = getData()
Insert cell
d3 = require('d3@5.15')
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