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

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