Published
Edited
Apr 22, 2021
1 fork
Insert cell
Insert cell
Insert cell
{
let height = 200;
let duration = 3000; //ms
let two = new Two({
type: Two.Types.canvas,
width: width,
height: height
});

let group = two.makeGroup();
group.translation.set(0, height - 20);

let data = generateData();

data = computeLayout(data, width, height - 20);

drawAxis(width);
data.forEach(d => {
let rect = two.makeRectangle(d.x, d.y, d.w, d.h);
rect.stroke = 'none';
rect.fill = 'grey';
rect.opacity = 0.8;
group.add(rect);
});

two.update();

function drawAxis(width) {
let xScale = d3.scaleBand()
.domain(data.map(n => n.key))
.range([0, width])
.paddingOuter(0.5)
.paddingInner(0.5);

let line = two.makeLine(0, 0, width, 0);
line.stroke = 'grey';
group.add(line);

data.forEach( d => {
let tick = two.makeLine(xScale(d.key), 0, xScale(d.key), 10);
tick.stroke = 'grey';
group.add(tick);

let text = two.makeText(d.key, xScale(d.key), 15);
text.size = 8;
text.fill = 'grey';
group.add(text);
});
}


return two.renderer.domElement;
}
Insert cell
function computeLayout(data, width, height) {

let xScale = d3.scaleBand()
.domain( data.map(n=>n.key) )
.range([0, width])
.paddingOuter(0.5)
.paddingInner(0.5);

let yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([0, height]);

data.forEach((d, i) => {
d.w = xScale.bandwidth();
d.h = yScale(d.value);

d.x = xScale(d.key);
d.y = -d.h/2;
});

return data;
}
Insert cell
function generateData() {
let maxValue = 400;
let data = [];

for (let i = 0; i < 50; i++) {
data.push({
key: i,
value: Math.floor(Math.random() * Math.floor(maxValue))
});
}

return data;
}
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