Published
Edited
Nov 20, 2020
Insert cell
md`# Horizontal-graph`
Insert cell
dataset = [
5,
25,
45,
65,
85,
105,
125,
145,
165,
185,
205,
225,
245,
265,
285,
305
]
Insert cell
bar_chart = {
const dataset = d3.shuffle(d3.range(40, 200, 10));
const width = 600;
const height = 300;
const svg = d3
.create('svg')
.attr('width', width)
.attr('height', height)
.attr('fill', '#064');

const barPadding = 1;

svg
.append('rect')
.attr('width', width)
.attr('height', height)
.attr('fill', 'yellow');

const rects = svg
.selectAll('rect.bar')
.data(dataset)
.join('rect')
.attr('class', 'bar');

rects
.attr('x', 0)
.attr('y', (d, i) => i * (height / dataset.length))
.attr('width', d => (d / d3.max(dataset)) * width)
.attr('height', height / dataset.length - barPadding)
.attr('fill', d => `hsl(220, 50%, ${60 - (d3 / d3.max(dataset)) * 40}%)`);

svg
.selectAll('text')
.data(dataset)
.join('text')
.attr('text-anchor', 'middle')
.attr('x', d => (d / d3.max(dataset)) * width - 20)
.attr(
'y',
(d, i) =>
i * (height / dataset.length) +
(height / dataset.length - barPadding) / 1.5
)
.attr('font-family', 'sans-serif')
.attr('font-weight', 'bold')
.attr('font-size', 11)
.attr('fill', 'white')
.text(d => d);

return svg.node();
}
Insert cell
d3 = require('d3@6')
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