Published
Edited
May 23, 2021
Insert cell
Insert cell
Insert cell
data = [
{name: 'Elizabeth', score: 98},
{name: 'Brian', score: 90},
{name: 'Taylor', score: 80},
{name: 'Kelly', score: 70},
{name: 'Jane', score: 45},
{name: 'Joe', score: 30},
]
Insert cell
Insert cell
Insert cell
Insert cell
margin = ({top: 10, bottom: 40, left: 50, right: 10})
Insert cell
visWidth = 600 - margin.left - margin.right
Insert cell
visHeight = 400 - margin.top - margin.bottom
Insert cell
Insert cell
Insert cell
names = data.map(d => d.name)
Insert cell
Insert cell
y = d3.scaleBand()
.domain(names)
.range([0, visHeight])
.padding(0.2)
Insert cell
Insert cell
y('Brian')
Insert cell
y('Taylor')
Insert cell
y('Joe')
Insert cell
Insert cell
y.bandwidth()
Insert cell
Insert cell
maxScore = d3.max(data, d => d.score)
Insert cell
Insert cell
x = d3.scaleLinear()
.domain([0, maxScore])
.range([0, visWidth])
Insert cell
Insert cell
x(0)
Insert cell
Insert cell
x(maxScore)
Insert cell
visWidth
Insert cell
Insert cell
x(maxScore / 2)
Insert cell
visWidth / 2
Insert cell
Insert cell
Insert cell
xAxis = d3.axisBottom(x)
Insert cell
yAxis = d3.axisLeft(y)
Insert cell
Insert cell
Insert cell
Insert cell
{
// create and select an svg element that is the size of the bars plus margins
const svg = d3.create('svg')
.attr('width', visWidth + margin.left + margin.right)
.attr('height', visHeight + margin.top + margin.bottom);
// append a group element and move it left and down to create space
// for the left and top margins
const g = svg.append("g")
.attr('transform', `translate(${margin.left}, ${margin.top})`);
// bind our data to rectangles
g.selectAll('rect')
.data(data)
.join('rect')
// set attributes for each bar
.attr('x', 0) // each bar starts at the same x position
.attr('y', d => y(d.name)) // pass the name to the y-scale to get y position
.attr('width', d => x(d.score)) // pass the score to the x-scale to get width of the bar
.attr('height', y.bandwidth()) // get the width of each band in the scale
.attr('fill', 'steelblue'); // color
// add a group for the y-axis
g.append('g')
.call(yAxis);
// add a group for the x-axis
g.append('g')
// we have to move this group down to the bottom of the vis
.attr('transform', `translate(0, ${visHeight})`)
.call(xAxis)
// add a label for the x-axis
.append('text')
.attr('fill', 'black')
.attr('font-family', 'sans-serif')
.attr('x', visWidth / 2)
.attr('y', 40)
.text("Score");
return svg.node();
}
Insert cell
Insert cell
Insert cell
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